From 2b3a1a3f79928ab6b3073e65e18a2c77a4acb767 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Thu, 29 Feb 2024 16:47:10 +0100 Subject: [PATCH 001/110] Add `depositorFeeDivisor` to Depositor contract To match the contract API from #91. --- core/contracts/TbtcDepositor.sol | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/contracts/TbtcDepositor.sol b/core/contracts/TbtcDepositor.sol index 732d289c0..d2644278d 100644 --- a/core/contracts/TbtcDepositor.sol +++ b/core/contracts/TbtcDepositor.sol @@ -4,6 +4,8 @@ pragma solidity ^0.8.21; import "@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol"; contract TbtcDepositor is AbstractTBTCDepositor { + uint64 public depositorFeeDivisor; + function initializeStakeRequest( IBridgeTypes.BitcoinTxInfo calldata fundingTx, IBridgeTypes.DepositRevealInfo calldata reveal, From 61dc761f2d2b7d2864fbc47938d25d2fb86fc7fd Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Thu, 29 Feb 2024 16:58:00 +0100 Subject: [PATCH 002/110] Estimate staking fees Add function that estimates the staking fees. Returns the following fees for staking operation: - treasuryFee - the tBTC treasury fee taken from each deposit and transferred to the treasury upon sweep proof submission. Is calculated based on the initial funding transaction amount, - optimisticMintingFee - the tBTC optimistic minting fee, Is calculated AFTER the treasury fee is cut, - depositTxMaxFee - maximum amount of BTC transaction fee that can be incurred by each swept deposit being part of the given sweep transaction, - depositorFee - the Acre network depositor fee taken from each deposit and transferred to the treasury upon stake request finalization. --- sdk/src/lib/contracts/tbtc-depositor.ts | 27 +++ sdk/src/lib/ethereum/tbtc-depositor.ts | 90 ++++++++++ sdk/test/lib/ethereum/tbtc-depositor.test.ts | 169 ++++++++++++++++++- sdk/test/utils/mock-acre-contracts.ts | 1 + 4 files changed, 279 insertions(+), 8 deletions(-) diff --git a/sdk/src/lib/contracts/tbtc-depositor.ts b/sdk/src/lib/contracts/tbtc-depositor.ts index 393221c36..ba14725b2 100644 --- a/sdk/src/lib/contracts/tbtc-depositor.ts +++ b/sdk/src/lib/contracts/tbtc-depositor.ts @@ -9,6 +9,31 @@ export type DecodedExtraData = { referral: number } +export type StakingFees = { + /** + * The tBTC treasury fee taken from each deposit and transferred to the + * treasury upon sweep proof submission. Is calculated based on the initial + * funding transaction amount. + */ + treasuryFee: bigint + /** + * The tBTC optimistic minting fee, Is calculated AFTER the treasury fee is + * cut. + */ + optimisticMintingFee: bigint + /** + * Maximum amount of BTC transaction fee that can + * be incurred by each swept deposit being part of the given sweep + * transaction. + */ + depositTxMaxFee: bigint + /** + * The Acre network depositor fee taken from each deposit and transferred to + * the treasury upon stake request finalization. + */ + depositorFee: bigint +} + /** * Interface for communication with the TBTCDepositor on-chain contract. */ @@ -35,4 +60,6 @@ export interface TBTCDepositor extends DepositorProxy { * @param extraData Encoded extra data. */ decodeExtraData(extraData: string): DecodedExtraData + + estimateStakingFees(amountToStake: bigint): Promise } diff --git a/sdk/src/lib/ethereum/tbtc-depositor.ts b/sdk/src/lib/ethereum/tbtc-depositor.ts index d46ddd310..8fa34cd30 100644 --- a/sdk/src/lib/ethereum/tbtc-depositor.ts +++ b/sdk/src/lib/ethereum/tbtc-depositor.ts @@ -7,12 +7,14 @@ import { isAddress, solidityPacked, zeroPadBytes, + Contract, } from "ethers" import { ChainIdentifier, DecodedExtraData, TBTCDepositor, DepositReceipt, + StakingFees, } from "../contracts" import { BitcoinRawTxVectors } from "../bitcoin" import { EthereumAddress } from "./address" @@ -26,6 +28,11 @@ import { EthereumNetwork } from "./network" import SepoliaTbtcDepositor from "./artifacts/sepolia/TbtcDepositor.json" +type TbtcDepositParameters = { + depositTreasuryFeeDivisor: bigint + depositTxMaxFee: bigint +} + /** * Ethereum implementation of the TBTCDepositor. */ @@ -36,6 +43,15 @@ class EthereumTBTCDepositor extends EthersContractWrapper implements TBTCDepositor { + /** + * Multiplier to convert satoshi to tBTC token units. + */ + readonly #satoshiMultiplier = 10n ** 10n + + #tbtcBridgeDepositsParameters: TbtcDepositParameters | undefined + + #tbtcOptimisticMintingFeeDivisor: bigint | undefined + constructor(config: EthersContractConfig, network: EthereumNetwork) { let artifact: EthersContractDeployment @@ -128,6 +144,80 @@ class EthereumTBTCDepositor return { staker, referral } } + + async estimateStakingFees(amountToStake: bigint): Promise { + const { depositTreasuryFeeDivisor, depositTxMaxFee } = + await this.#getTbtcDepositParameters() + + const treasuryFee = amountToStake / depositTreasuryFeeDivisor + + // Both deposit amount and treasury fee are in the 1e8 satoshi precision. + // We need to convert them to the 1e18 TBTC precision. + const amountSubTreasury = + (amountToStake - treasuryFee) * this.#satoshiMultiplier + + const optimisticMintingFeeDivisor = + await this.#getTbtcOptimisticMintingFeeDivisor() + const optimisticMintingFee = + optimisticMintingFeeDivisor > 0 + ? amountSubTreasury / optimisticMintingFeeDivisor + : 0n + + const depositorFeeDivisor = await this.instance.depositorFeeDivisor() + // Compute depositor fee. The fee is calculated based on the initial funding + // transaction amount, before the tBTC protocol network fees were taken. + const depositorFee = + depositorFeeDivisor > 0n + ? (amountToStake * this.#satoshiMultiplier) / depositorFeeDivisor + : 0n + + // TODO: Maybe we should group fees by network? Eg.: + // `const fess = { tbtc: {...}, acre: {...}}` + return { + treasuryFee: treasuryFee * this.#satoshiMultiplier, + optimisticMintingFee, + depositTxMaxFee: depositTxMaxFee * this.#satoshiMultiplier, + depositorFee, + } + } + + async #getTbtcDepositParameters(): Promise { + if (this.#tbtcBridgeDepositsParameters) { + return this.#tbtcBridgeDepositsParameters + } + + const bridgeAddress = await this.instance.bridge() + + const bridge = new Contract(bridgeAddress, [ + "function depositsParameters()", + ]) + + const depositsParameters = + (await bridge.depositsParameters()) as TbtcDepositParameters + + this.#tbtcBridgeDepositsParameters = depositsParameters + + return depositsParameters + } + + async #getTbtcOptimisticMintingFeeDivisor(): Promise { + if (this.#tbtcOptimisticMintingFeeDivisor) { + return this.#tbtcOptimisticMintingFeeDivisor + } + + const vaultAddress = await this.getTbtcVaultChainIdentifier() + + const vault = new Contract(`0x${vaultAddress.identifierHex}`, [ + "function optimisticMintingFeeDivisor()", + ]) + + const optimisticMintingFeeDivisor = + (await vault.optimisticMintingFeeDivisor()) as bigint + + this.#tbtcOptimisticMintingFeeDivisor = optimisticMintingFeeDivisor + + return optimisticMintingFeeDivisor + } } export { EthereumTBTCDepositor, packRevealDepositParameters } diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index 2edca897f..9add365cb 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -1,9 +1,10 @@ -import ethers, { Contract, ZeroAddress } from "ethers" +import ethers, { Contract, ZeroAddress, getAddress } from "ethers" import { EthereumTBTCDepositor, EthereumAddress, Hex, EthereumSigner, + StakingFees, } from "../../../src" import { extraDataValidTestData } from "./data" @@ -12,26 +13,44 @@ jest.mock("ethers", (): object => ({ ...jest.requireActual("ethers"), })) +const testData = { + depositorFeeDivisor: 1000n, + depositParameters: { + depositTreasuryFeeDivisor: 2_000n, // 1/2000 == 5bps == 0.05% == 0.0005 + depositTxMaxFee: 100_000n, // 100000 satoshi = 0.001 BTC + }, + optimisticMintingFeeDivisor: 500n, // 1/500 = 0.002 = 0.2%0 +} + describe("TBTCDepositor", () => { const spyOnEthersDataSlice = jest.spyOn(ethers, "dataSlice") + const spyOnEthersContract = jest.spyOn(ethers, "Contract") const vaultAddress = EthereumAddress.from( ethers.Wallet.createRandom().address, ) + const bridgeAddress = EthereumAddress.from( + ethers.Wallet.createRandom().address, + ) const mockedContractInstance = { - tbtcVault: jest.fn().mockImplementation(() => vaultAddress.identifierHex), + tbtcVault: jest + .fn() + .mockImplementation(() => `0x${vaultAddress.identifierHex}`), initializeStakeRequest: jest.fn(), + bridge: jest.fn().mockResolvedValue(`0x${bridgeAddress.identifierHex}`), + depositorFeeDivisor: jest + .fn() + .mockResolvedValue(testData.depositorFeeDivisor), } + let depositor: EthereumTBTCDepositor let depositorAddress: EthereumAddress - beforeEach(async () => { - jest - .spyOn(ethers, "Contract") - .mockImplementationOnce( - () => mockedContractInstance as unknown as Contract, - ) + beforeAll(async () => { + spyOnEthersContract.mockImplementationOnce( + () => mockedContractInstance as unknown as Contract, + ) // TODO: get the address from artifact imported from `core` package. depositorAddress = EthereumAddress.from( @@ -243,4 +262,138 @@ describe("TBTCDepositor", () => { }, ) }) + + describe("estimateStakingFees", () => { + const mockedBridgeContractInstance = { + depositsParameters: jest + .fn() + .mockResolvedValue(testData.depositParameters), + } + + const mockedVaultContractInstance = { + optimisticMintingFeeDivisor: jest + .fn() + .mockResolvedValue(testData.optimisticMintingFeeDivisor), + } + + const amountToStake = 10_000_000n // 0.1 BTC + + const expectedResult = { + // The fee is calculated based on the initial funding + // transaction amount. `amountToStake / depositTreasuryFeeDivisor` + // 0.00005 tBTC in 1e18 precision. + treasuryFee: 50000000000000n, + // Maximum amount of BTC transaction fee that can + // be incurred by each swept deposit being part of the given sweep + // transaction. + // 0.001 tBTC in 1e18 precision. + depositTxMaxFee: 1000000000000000n, + // Divisor used to compute the depositor fee taken from each deposit + // and transferred to the treasury upon stake request finalization. + // `depositorFee = depositedAmount / depositorFeeDivisor` + // 0.0001 tBTC in 1e18 precision. + depositorFee: 100000000000000n, + // The optimistic fee is a percentage AFTER + // the treasury fee is cut: + // `fee = (depositAmount - treasuryFee) / optimisticMintingFeeDivisor` + // 0.0001999 tBTC in 1e18 precision. + optimisticMintingFee: 199900000000000n, + } + + beforeAll(() => { + spyOnEthersContract.mockClear() + + spyOnEthersContract.mockImplementation((target: string) => { + if (getAddress(target) === getAddress(bridgeAddress.identifierHex)) + return mockedBridgeContractInstance as unknown as Contract + if (getAddress(target) === getAddress(vaultAddress.identifierHex)) + return mockedVaultContractInstance as unknown as Contract + + throw new Error("Cannot create mocked contract instance") + }) + }) + + describe("when network fees are not yet cached", () => { + let result: StakingFees + + beforeAll(async () => { + result = await depositor.estimateStakingFees(amountToStake) + }) + + it("should get the bridge contract address", () => { + expect(mockedContractInstance.bridge).toHaveBeenCalled() + }) + + it("should create the ethers Contract instance of the Bridge contract", () => { + expect(Contract).toHaveBeenNthCalledWith( + 1, + `0x${bridgeAddress.identifierHex}`, + ["function depositsParameters()"], + ) + }) + + it("should get the deposit parameters from chain", () => { + expect( + mockedBridgeContractInstance.depositsParameters, + ).toHaveBeenCalled() + }) + + it("should get the vault contract address", () => { + expect(mockedContractInstance.tbtcVault).toHaveBeenCalled() + }) + + it("should create the ethers Contract instance of the Bridge contract", () => { + expect(Contract).toHaveBeenNthCalledWith( + 2, + `0x${vaultAddress.identifierHex}`, + ["function optimisticMintingFeeDivisor()"], + ) + }) + + it("should get the optimistic minting fee divisor", () => { + expect( + mockedVaultContractInstance.optimisticMintingFeeDivisor, + ).toHaveBeenCalled() + }) + + it("should get the depositor fee divisor", () => { + expect(mockedContractInstance.depositorFeeDivisor).toHaveBeenCalled() + }) + + it("should return correct fees", () => { + expect(result).toMatchObject(expectedResult) + }) + }) + + describe("when network fees are already cached", () => { + let result2: StakingFees + + beforeAll(async () => { + mockedContractInstance.bridge.mockClear() + mockedContractInstance.tbtcVault.mockClear() + mockedBridgeContractInstance.depositsParameters.mockClear() + mockedVaultContractInstance.optimisticMintingFeeDivisor.mockClear() + + result2 = await depositor.estimateStakingFees(amountToStake) + }) + + it("should get the deposit parameters from cache", () => { + expect(mockedContractInstance.bridge).toHaveBeenCalledTimes(0) + expect( + mockedBridgeContractInstance.depositsParameters, + ).toHaveBeenCalledTimes(0) + }) + + it("should get the optimistic minting fee divisor from cache", () => { + expect(mockedContractInstance.tbtcVault).toHaveBeenCalledTimes(0) + expect( + mockedVaultContractInstance.optimisticMintingFeeDivisor, + ).toHaveBeenCalledTimes(0) + }) + + it("should return correct fees", () => { + expect(result2).toMatchObject(expectedResult) + }) + }) + }) }) diff --git a/sdk/test/utils/mock-acre-contracts.ts b/sdk/test/utils/mock-acre-contracts.ts index 111554b39..96c3feb23 100644 --- a/sdk/test/utils/mock-acre-contracts.ts +++ b/sdk/test/utils/mock-acre-contracts.ts @@ -11,6 +11,7 @@ export class MockAcreContracts implements AcreContracts { decodeExtraData: jest.fn(), encodeExtraData: jest.fn(), revealDeposit: jest.fn(), + estimateStakingFees: jest.fn(), } as TBTCDepositor } } From 7bbdcf8e145cb55e376852ab81dc5e811905ab8c Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Thu, 29 Feb 2024 17:03:56 +0100 Subject: [PATCH 003/110] Expose fee breakdown for staking operation Expose fee breakdown for staking opeartion in staking `module`. --- sdk/src/modules/staking/index.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sdk/src/modules/staking/index.ts b/sdk/src/modules/staking/index.ts index f4fd6b181..94a8853bf 100644 --- a/sdk/src/modules/staking/index.ts +++ b/sdk/src/modules/staking/index.ts @@ -1,5 +1,5 @@ import { ChainIdentifier, TBTC } from "@keep-network/tbtc-v2.ts" -import { AcreContracts, DepositorProxy } from "../../lib/contracts" +import { AcreContracts, DepositorProxy, StakingFees } from "../../lib/contracts" import { ChainEIP712Signer } from "../../lib/eip712-signer" import { StakeInitialization } from "./stake-initialization" @@ -62,6 +62,10 @@ class StakingModule { deposit, ) } + + async estimateStakingFees(amount: bigint): Promise { + return this.#contracts.tbtcDepositor.estimateStakingFees(amount) + } } export { StakingModule, StakeInitialization } From 0f3a8e4071f45e6bac5de619bae97f9979503b45 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Thu, 7 Mar 2024 11:33:23 +0100 Subject: [PATCH 004/110] Read the min amount of BTC deposit from the SDK --- .../StakeFormModal/StakeDetails.tsx | 4 +-- .../StakeFormModal/index.tsx | 9 ++++--- .../UnstakeFormModal/index.tsx | 7 ++++-- .../shared/TokenAmountForm/index.tsx | 2 +- dapp/src/constants/currency.ts | 4 +-- dapp/src/constants/staking.ts | 10 -------- dapp/src/hooks/index.ts | 2 +- dapp/src/hooks/sdk/index.ts | 3 +++ .../src/hooks/sdk/useFetchMinDepositAmount.ts | 25 +++++++++++++++++++ dapp/src/hooks/sdk/useFetchSdkData.ts | 5 ++++ .../hooks/{ => sdk}/useInitializeAcreSdk.ts | 2 +- dapp/src/hooks/useInitApp.ts | 3 ++- dapp/src/store/btc/btcSelector.ts | 3 +++ dapp/src/store/btc/btcSlice.ts | 10 +++++++- dapp/src/store/middleware.ts | 9 ++++++- dapp/src/utils/forms.ts | 7 +++--- dapp/src/utils/numbers.ts | 6 ----- 17 files changed, 75 insertions(+), 36 deletions(-) create mode 100644 dapp/src/hooks/sdk/index.ts create mode 100644 dapp/src/hooks/sdk/useFetchMinDepositAmount.ts create mode 100644 dapp/src/hooks/sdk/useFetchSdkData.ts rename dapp/src/hooks/{ => sdk}/useInitializeAcreSdk.ts (90%) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/StakeDetails.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/StakeDetails.tsx index bba5a7c28..80d066454 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/StakeDetails.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/StakeDetails.tsx @@ -11,12 +11,12 @@ function StakeDetails({ maxTokenAmount, }: { currency: CurrencyType - minTokenAmount: string + minTokenAmount: bigint maxTokenAmount: string }) { const value = useTokenAmountFormValue() ?? 0n const isMaximumValueExceeded = value > BigInt(maxTokenAmount) - const isMinimumValueFulfilled = value >= BigInt(minTokenAmount) + const isMinimumValueFulfilled = value >= minTokenAmount // Let's not calculate the details of the transaction when the value is not valid. const amount = !isMaximumValueExceeded && isMinimumValueFulfilled ? value : 0n const details = useTransactionDetails(amount) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx index 5f80d9576..1f97f0d88 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx @@ -1,9 +1,9 @@ import React from "react" -import { BITCOIN_MIN_AMOUNT } from "#/constants" import TokenAmountForm from "#/components/shared/TokenAmountForm" import { TokenAmountFormValues } from "#/components/shared/TokenAmountForm/TokenAmountFormBase" -import { useWalletContext } from "#/hooks" +import { useAppSelector, useWalletContext } from "#/hooks" import { FormSubmitButton } from "#/components/shared/Form" +import { selectMinDepositAmount } from "#/store/btc" import StakeDetails from "./StakeDetails" function StakeFormModal({ @@ -11,6 +11,7 @@ function StakeFormModal({ }: { onSubmitForm: (values: TokenAmountFormValues) => void }) { + const minDepositAmount = useAppSelector(selectMinDepositAmount) const { btcAccount } = useWalletContext() const tokenBalance = btcAccount?.balance.toString() ?? "0" @@ -19,12 +20,12 @@ function StakeFormModal({ tokenBalanceInputPlaceholder="BTC" currency="bitcoin" tokenBalance={tokenBalance} - minTokenAmount={BITCOIN_MIN_AMOUNT} + minTokenAmount={minDepositAmount} onSubmitForm={onSubmitForm} > Stake diff --git a/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx index 85ec4c38e..561ec08eb 100644 --- a/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx @@ -1,11 +1,12 @@ import React from "react" import { Card, CardBody, Flex, HStack } from "@chakra-ui/react" -import { BITCOIN_MIN_AMOUNT } from "#/constants" import TokenAmountForm from "#/components/shared/TokenAmountForm" import { TokenAmountFormValues } from "#/components/shared/TokenAmountForm/TokenAmountFormBase" import { TextMd, TextSm } from "#/components/shared/Typography" import Spinner from "#/components/shared/Spinner" import { FormSubmitButton } from "#/components/shared/Form" +import { useAppSelector } from "#/hooks" +import { selectMinDepositAmount } from "#/store/btc" import UnstakeDetails from "./UnstakeDetails" // TODO: Use a position amount @@ -16,12 +17,14 @@ function UnstakeFormModal({ }: { onSubmitForm: (values: TokenAmountFormValues) => void }) { + const minDepositAmount = useAppSelector(selectMinDepositAmount) + return ( diff --git a/dapp/src/components/shared/TokenAmountForm/index.tsx b/dapp/src/components/shared/TokenAmountForm/index.tsx index d8c6fabf0..80850c4e0 100644 --- a/dapp/src/components/shared/TokenAmountForm/index.tsx +++ b/dapp/src/components/shared/TokenAmountForm/index.tsx @@ -7,7 +7,7 @@ import TokenAmountFormBase, { type TokenAmountFormProps = { onSubmitForm: (values: TokenAmountFormValues) => void - minTokenAmount: string + minTokenAmount: bigint } & TokenAmountFormBaseProps const TokenAmountForm = withFormik( diff --git a/dapp/src/constants/currency.ts b/dapp/src/constants/currency.ts index de7a788d7..483da1dbd 100644 --- a/dapp/src/constants/currency.ts +++ b/dapp/src/constants/currency.ts @@ -1,13 +1,13 @@ import { Currency, CurrencyType } from "#/types" import { EthereumNetwork } from "@acre-btc/sdk" import { ETHEREUM_NETWORK } from "./chains" -import { BITCOIN_DESIRED_DECIMALS } from "./staking" export const BITCOIN: Currency = { name: "Bitcoin", symbol: "BTC", decimals: 8, - desiredDecimals: BITCOIN_DESIRED_DECIMALS, + // TODO: Change when min amount of BTC will be updated + desiredDecimals: 5, } export const STBTC: Currency = { diff --git a/dapp/src/constants/staking.ts b/dapp/src/constants/staking.ts index c7e2e980d..f7664b0f2 100644 --- a/dapp/src/constants/staking.ts +++ b/dapp/src/constants/staking.ts @@ -1,11 +1 @@ -import { getDesiredDecimals } from "#/utils/numbers" - -// TODO: Read the value from the SDK, once we expose it -export const BITCOIN_MIN_AMOUNT = String(1e4) // 0.0001 BTC - -export const BITCOIN_DESIRED_DECIMALS = getDesiredDecimals( - BITCOIN_MIN_AMOUNT, - 8, -) - export const REFERRAL = import.meta.env.VITE_REFERRAL diff --git a/dapp/src/hooks/index.ts b/dapp/src/hooks/index.ts index 292568f86..85b80fdb3 100644 --- a/dapp/src/hooks/index.ts +++ b/dapp/src/hooks/index.ts @@ -1,4 +1,5 @@ export * from "./store" +export * from "./sdk" export * from "./useDetectThemeMode" export * from "./useRequestBitcoinAccount" export * from "./useRequestEthereumAccount" @@ -9,7 +10,6 @@ export * from "./useModalFlowContext" export * from "./useTransactionContext" export * from "./useTransactionDetails" export * from "./useDepositBTCTransaction" -export * from "./useInitializeAcreSdk" export * from "./useTransactionHistoryTable" export * from "./useExecuteFunction" export * from "./useStakeFlowContext" diff --git a/dapp/src/hooks/sdk/index.ts b/dapp/src/hooks/sdk/index.ts new file mode 100644 index 000000000..73d11a6c9 --- /dev/null +++ b/dapp/src/hooks/sdk/index.ts @@ -0,0 +1,3 @@ +export * from "./useInitializeAcreSdk" +export * from "./useFetchMinDepositAmount" +export * from "./useFetchSdkData" diff --git a/dapp/src/hooks/sdk/useFetchMinDepositAmount.ts b/dapp/src/hooks/sdk/useFetchMinDepositAmount.ts new file mode 100644 index 000000000..b9354890f --- /dev/null +++ b/dapp/src/hooks/sdk/useFetchMinDepositAmount.ts @@ -0,0 +1,25 @@ +import { useEffect } from "react" +import { setMinDepositAmount } from "#/store/btc" +import { logPromiseFailure } from "#/utils" +import { useAcreContext } from "#/acre-react/hooks" +import { useAppDispatch } from "../store/useAppDispatch" + +export function useFetchMinDepositAmount() { + const { acre, isInitialized } = useAcreContext() + const dispatch = useAppDispatch() + + useEffect(() => { + if (!isInitialized || !acre) return + + const fetchMinDepositAmount = async () => { + // TODO: Use function from SDK + const minDepositAmount = await new Promise((resolve) => { + resolve(BigInt(String(1e4))) // 0.0001 BTC + }) + + dispatch(setMinDepositAmount(minDepositAmount)) + } + + logPromiseFailure(fetchMinDepositAmount()) + }, [acre, dispatch, isInitialized]) +} diff --git a/dapp/src/hooks/sdk/useFetchSdkData.ts b/dapp/src/hooks/sdk/useFetchSdkData.ts new file mode 100644 index 000000000..083619881 --- /dev/null +++ b/dapp/src/hooks/sdk/useFetchSdkData.ts @@ -0,0 +1,5 @@ +import { useFetchMinDepositAmount } from "./useFetchMinDepositAmount" + +export function useFetchSdkData() { + useFetchMinDepositAmount() +} diff --git a/dapp/src/hooks/useInitializeAcreSdk.ts b/dapp/src/hooks/sdk/useInitializeAcreSdk.ts similarity index 90% rename from dapp/src/hooks/useInitializeAcreSdk.ts rename to dapp/src/hooks/sdk/useInitializeAcreSdk.ts index ab05a9aac..56af453e1 100644 --- a/dapp/src/hooks/useInitializeAcreSdk.ts +++ b/dapp/src/hooks/sdk/useInitializeAcreSdk.ts @@ -2,7 +2,7 @@ import { useEffect } from "react" import { ETHEREUM_NETWORK } from "#/constants" import { logPromiseFailure } from "#/utils" import { useAcreContext } from "#/acre-react/hooks" -import { useWalletContext } from "./useWalletContext" +import { useWalletContext } from "../useWalletContext" export function useInitializeAcreSdk() { const { ethAccount } = useWalletContext() diff --git a/dapp/src/hooks/useInitApp.ts b/dapp/src/hooks/useInitApp.ts index bfa07283e..7065f102b 100644 --- a/dapp/src/hooks/useInitApp.ts +++ b/dapp/src/hooks/useInitApp.ts @@ -1,5 +1,5 @@ +import { useFetchSdkData, useInitializeAcreSdk } from "./sdk" import { useSentry } from "./sentry" -import { useInitializeAcreSdk } from "./useInitializeAcreSdk" import { useFetchBTCPriceUSD } from "./useFetchBTCPriceUSD" export function useInitApp() { @@ -7,5 +7,6 @@ export function useInitApp() { // useDetectThemeMode() useSentry() useInitializeAcreSdk() + useFetchSdkData() useFetchBTCPriceUSD() } diff --git a/dapp/src/store/btc/btcSelector.ts b/dapp/src/store/btc/btcSelector.ts index c8ae200ab..fe95c9429 100644 --- a/dapp/src/store/btc/btcSelector.ts +++ b/dapp/src/store/btc/btcSelector.ts @@ -1,3 +1,6 @@ import { RootState } from ".." export const selectBtcUsdPrice = (state: RootState) => state.btc.usdPrice + +export const selectMinDepositAmount = (state: RootState) => + state.btc.minDepositAmount diff --git a/dapp/src/store/btc/btcSlice.ts b/dapp/src/store/btc/btcSlice.ts index 84468710d..c4bda064b 100644 --- a/dapp/src/store/btc/btcSlice.ts +++ b/dapp/src/store/btc/btcSlice.ts @@ -4,18 +4,24 @@ import { fetchBTCPriceUSD } from "./btcThunk" type BtcState = { isLoadingPriceUSD: boolean usdPrice: number + minDepositAmount: bigint } const initialState: BtcState = { isLoadingPriceUSD: false, usdPrice: 0, + minDepositAmount: 0n, } // Store Bitcoin data such as balance, balance in usd and other related data to Bitcoin chain. export const btcSlice = createSlice({ name: "btc", initialState, - reducers: {}, + reducers: { + setMinDepositAmount(state, action: PayloadAction) { + state.minDepositAmount = action.payload + }, + }, extraReducers: (builder) => { builder.addCase(fetchBTCPriceUSD.pending, (state) => { state.isLoadingPriceUSD = true @@ -32,3 +38,5 @@ export const btcSlice = createSlice({ ) }, }) + +export const { setMinDepositAmount } = btcSlice.actions diff --git a/dapp/src/store/middleware.ts b/dapp/src/store/middleware.ts index 451fd90f1..80413c5ce 100644 --- a/dapp/src/store/middleware.ts +++ b/dapp/src/store/middleware.ts @@ -1 +1,8 @@ -export const middleware = {} +import { isPlain } from "@reduxjs/toolkit" + +export const middleware = { + serializableCheck: { + isSerializable: (value: unknown) => + isPlain(value) || typeof value === "bigint", + }, +} diff --git a/dapp/src/utils/forms.ts b/dapp/src/utils/forms.ts index ba11af6d1..193b469b0 100644 --- a/dapp/src/utils/forms.ts +++ b/dapp/src/utils/forms.ts @@ -18,7 +18,7 @@ export function getErrorsObj(errors: { [key in keyof T]: string }) { export function validateTokenAmount( value: bigint | undefined, maxValue: string, - minValue: string, + minValue: bigint, currency: CurrencyType, ): string | undefined { if (value === undefined) return ERRORS.REQUIRED @@ -26,15 +26,14 @@ export function validateTokenAmount( const { decimals } = getCurrencyByType(currency) const maxValueInBI = BigInt(maxValue) - const minValueInBI = BigInt(minValue) const isMaximumValueExceeded = value > maxValueInBI - const isMinimumValueFulfilled = value >= minValueInBI + const isMinimumValueFulfilled = value >= minValue if (isMaximumValueExceeded) return ERRORS.EXCEEDED_VALUE if (!isMinimumValueFulfilled) return ERRORS.INSUFFICIENT_VALUE( - fixedPointNumberToString(BigInt(minValue), decimals), + fixedPointNumberToString(minValue, decimals), ) return undefined diff --git a/dapp/src/utils/numbers.ts b/dapp/src/utils/numbers.ts index 70fa2c307..18e629e0c 100644 --- a/dapp/src/utils/numbers.ts +++ b/dapp/src/utils/numbers.ts @@ -200,9 +200,3 @@ export function userAmountToBigInt( // Generates a random integer in min-max range (inclusively) export const randomInteger = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min - -export function getDesiredDecimals(amount: string | number, decimals: number) { - const undecimaledAmount = amount.toString() - const desiredDecimals = decimals - undecimaledAmount.length + 1 - return desiredDecimals > 0 ? desiredDecimals : 2 -} From 836a30009160fc4c59a140159ca593e9b04e8215 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Thu, 7 Mar 2024 11:59:05 +0100 Subject: [PATCH 005/110] Use a `bigint` type in `StakeDetails` and validation --- .../ActiveStakingStep/StakeFormModal/StakeDetails.tsx | 4 ++-- .../ActiveStakingStep/StakeFormModal/index.tsx | 2 +- dapp/src/components/shared/TokenAmountForm/index.tsx | 2 +- dapp/src/utils/forms.ts | 6 ++---- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/StakeDetails.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/StakeDetails.tsx index 80d066454..9f6d8ebf3 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/StakeDetails.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/StakeDetails.tsx @@ -12,10 +12,10 @@ function StakeDetails({ }: { currency: CurrencyType minTokenAmount: bigint - maxTokenAmount: string + maxTokenAmount: bigint }) { const value = useTokenAmountFormValue() ?? 0n - const isMaximumValueExceeded = value > BigInt(maxTokenAmount) + const isMaximumValueExceeded = value > maxTokenAmount const isMinimumValueFulfilled = value >= minTokenAmount // Let's not calculate the details of the transaction when the value is not valid. const amount = !isMaximumValueExceeded && isMinimumValueFulfilled ? value : 0n diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx index 1f97f0d88..d7afc24cf 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx @@ -26,7 +26,7 @@ function StakeFormModal({ Stake diff --git a/dapp/src/components/shared/TokenAmountForm/index.tsx b/dapp/src/components/shared/TokenAmountForm/index.tsx index 80850c4e0..73d09935c 100644 --- a/dapp/src/components/shared/TokenAmountForm/index.tsx +++ b/dapp/src/components/shared/TokenAmountForm/index.tsx @@ -20,7 +20,7 @@ const TokenAmountForm = withFormik( errors.amount = validateTokenAmount( amount, - tokenBalance, + BigInt(tokenBalance), minTokenAmount, currency, ) diff --git a/dapp/src/utils/forms.ts b/dapp/src/utils/forms.ts index 193b469b0..d1c8caf4f 100644 --- a/dapp/src/utils/forms.ts +++ b/dapp/src/utils/forms.ts @@ -17,7 +17,7 @@ export function getErrorsObj(errors: { [key in keyof T]: string }) { export function validateTokenAmount( value: bigint | undefined, - maxValue: string, + maxValue: bigint, minValue: bigint, currency: CurrencyType, ): string | undefined { @@ -25,9 +25,7 @@ export function validateTokenAmount( const { decimals } = getCurrencyByType(currency) - const maxValueInBI = BigInt(maxValue) - - const isMaximumValueExceeded = value > maxValueInBI + const isMaximumValueExceeded = value > maxValue const isMinimumValueFulfilled = value >= minValue if (isMaximumValueExceeded) return ERRORS.EXCEEDED_VALUE From b4541c5c6276c9f6c2d6eb18ef63b27a9fcfe348 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Fri, 8 Mar 2024 11:25:17 +0100 Subject: [PATCH 006/110] Add a theme for `CloseButton` --- .../components/shared/ActivityBar/ActivityCard.tsx | 6 +----- dapp/src/theme/CloseButton.ts | 11 +++++++++++ dapp/src/theme/index.ts | 2 ++ 3 files changed, 14 insertions(+), 5 deletions(-) create mode 100644 dapp/src/theme/CloseButton.ts diff --git a/dapp/src/components/shared/ActivityBar/ActivityCard.tsx b/dapp/src/components/shared/ActivityBar/ActivityCard.tsx index 96e8cc8ba..8682c0964 100644 --- a/dapp/src/components/shared/ActivityBar/ActivityCard.tsx +++ b/dapp/src/components/shared/ActivityBar/ActivityCard.tsx @@ -51,11 +51,7 @@ function ActivityCard({ activity, onRemove }: ActivityCardType) { /> {isCompleted ? ( - + ) : ( Date: Tue, 12 Mar 2024 10:55:08 +0100 Subject: [PATCH 007/110] Restructure the styles for the Alert component According to styleguide, we need to update the styles for the Alert component. Additionally, the Toast component is based on the basic styles of Alert. Therefore, now the Alert component is based on the styleguide. However, a separate CardAlert component was created to contain the styles of the previous alert in one place. --- dapp/src/assets/icons/AlertError.tsx | 17 ++++++ dapp/src/assets/icons/AlertInfo.tsx | 25 ++++----- dapp/src/assets/icons/index.ts | 1 + .../ActiveStakingStep/DepositBTCModal.tsx | 6 +-- .../ActiveStakingStep/SignMessageModal.tsx | 4 +- .../ActiveUnstakingStep/SignMessageModal.tsx | 4 +- .../MissingAccountModal.tsx | 6 +-- .../ModalContentWrapper/SuccessModal.tsx | 4 +- dapp/src/components/shared/Alert.tsx | 52 +++++++++++++++++++ dapp/src/components/shared/Alert/index.tsx | 49 ----------------- dapp/src/components/shared/CardAlert.tsx | 51 ++++++++++++++++++ .../index.tsx => ReceiveSTBTCAlert.tsx} | 8 +-- dapp/src/components/shared/Toast.tsx | 26 ++++++++++ dapp/src/theme/Alert.ts | 44 +++++++--------- dapp/src/theme/utils/colors.ts | 3 ++ 15 files changed, 193 insertions(+), 107 deletions(-) create mode 100644 dapp/src/assets/icons/AlertError.tsx create mode 100644 dapp/src/components/shared/Alert.tsx delete mode 100644 dapp/src/components/shared/Alert/index.tsx create mode 100644 dapp/src/components/shared/CardAlert.tsx rename dapp/src/components/shared/{AlertReceiveSTBTC/index.tsx => ReceiveSTBTCAlert.tsx} (66%) create mode 100644 dapp/src/components/shared/Toast.tsx diff --git a/dapp/src/assets/icons/AlertError.tsx b/dapp/src/assets/icons/AlertError.tsx new file mode 100644 index 000000000..6fb513e5b --- /dev/null +++ b/dapp/src/assets/icons/AlertError.tsx @@ -0,0 +1,17 @@ +import React from "react" +import { createIcon } from "@chakra-ui/react" + +export const AlertError = createIcon({ + displayName: "AlertError", + viewBox: "0 0 24 25", + path: [ + , + ], +}) diff --git a/dapp/src/assets/icons/AlertInfo.tsx b/dapp/src/assets/icons/AlertInfo.tsx index a1c8cf1ad..2eda75539 100644 --- a/dapp/src/assets/icons/AlertInfo.tsx +++ b/dapp/src/assets/icons/AlertInfo.tsx @@ -3,22 +3,15 @@ import { createIcon } from "@chakra-ui/react" export const AlertInfo = createIcon({ displayName: "AlertInfo", - viewBox: "0 0 16 16", + viewBox: "0 0 24 24", path: [ - - - , - - - - - , + , ], }) diff --git a/dapp/src/assets/icons/index.ts b/dapp/src/assets/icons/index.ts index 347ef098c..5be87f41a 100644 --- a/dapp/src/assets/icons/index.ts +++ b/dapp/src/assets/icons/index.ts @@ -8,6 +8,7 @@ export * from "./AcreLogo" export * from "./ConnectBTCAccount" export * from "./ConnectETHAccount" export * from "./AlertInfo" +export * from "./AlertError" export * from "./stBTC" export * from "./BTC" export * from "./ShieldPlus" diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index 1701afbe5..0cf29d605 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -8,10 +8,10 @@ import { useTransactionContext, useWalletContext, } from "#/hooks" -import Alert from "#/components/shared/Alert" import { TextMd } from "#/components/shared/Typography" import { logPromiseFailure } from "#/utils" import { PROCESS_STATUSES } from "#/types" +import CardAlert from "#/components/shared/CardAlert" import StakingStepsModalContent from "./StakingStepsModalContent" export default function DepositBTCModal() { @@ -82,11 +82,11 @@ export default function DepositBTCModal() { activeStep={1} onClick={handledDepositBTCWrapper} > - + Make a Bitcoin transaction to deposit and stake your BTC. - + ) } diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx index 84803da08..d8b059795 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx @@ -5,8 +5,8 @@ import { useStakeFlowContext, } from "#/hooks" import { logPromiseFailure } from "#/utils" -import AlertReceiveSTBTC from "#/components/shared/AlertReceiveSTBTC" import { PROCESS_STATUSES } from "#/types" +import ReceiveSTBTCAlert from "#/components/shared/ReceiveSTBTCAlert" import StakingStepsModalContent from "./StakingStepsModalContent" export default function SignMessageModal() { @@ -28,7 +28,7 @@ export default function SignMessageModal() { activeStep={0} onClick={handleSignMessageWrapper} > - + ) } diff --git a/dapp/src/components/TransactionModal/ActiveUnstakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveUnstakingStep/SignMessageModal.tsx index 0f9bd1003..0828456f9 100644 --- a/dapp/src/components/TransactionModal/ActiveUnstakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveUnstakingStep/SignMessageModal.tsx @@ -3,8 +3,8 @@ import { useExecuteFunction, useModalFlowContext } from "#/hooks" import { PROCESS_STATUSES } from "#/types" import { Button, ModalBody, ModalFooter, ModalHeader } from "@chakra-ui/react" import { TextMd } from "#/components/shared/Typography" -import AlertReceiveSTBTC from "#/components/shared/AlertReceiveSTBTC" import { logPromiseFailure } from "#/utils" +import ReceiveSTBTCAlert from "#/components/shared/ReceiveSTBTCAlert" export default function SignMessageModal() { const { setStatus } = useModalFlowContext() @@ -46,7 +46,7 @@ export default function SignMessageModal() { You will sign a gas-free Ethereum message to indicate the address where you'd like to get your stBTC liquid staking token. - + + + + ), + }) + + const showToast = useCallback(() => { + if (!toast.isActive(type)) { + toast({ id: type }) + } + }, [toast, type]) + + useEffect(() => { + if (isToastClosed) return + + const timeout = setTimeout(showToast, delay) + + // eslint-disable-next-line consistent-return + return () => clearTimeout(timeout) + }, [delay, isToastClosed, showToast]) + + useEffect(() => { + if (!account || isToastClosed) return + + toast.close(type) + setIsToastClosed(true) + }, [account, isToastClosed, toast, type]) +} diff --git a/dapp/src/pages/OverviewPage/index.tsx b/dapp/src/pages/OverviewPage/index.tsx index 54bb52d8b..5ec9fb351 100644 --- a/dapp/src/pages/OverviewPage/index.tsx +++ b/dapp/src/pages/OverviewPage/index.tsx @@ -1,6 +1,6 @@ import React from "react" import { Flex, Grid, HStack, Switch } from "@chakra-ui/react" -import { useDocsDrawer } from "#/hooks" +import { useDocsDrawer, useWalletContext } from "#/hooks" import { TextSm } from "#/components/shared/Typography" import { USD } from "#/constants" import ButtonLink from "#/components/shared/ButtonLink" @@ -11,20 +11,37 @@ import ActivityBar from "../../components/shared/ActivityBar" export default function OverviewPage() { const { onOpen } = useDocsDrawer() + const { isConnected } = useWalletContext() return ( - - - {/* TODO: Handle click actions */} - - Show values in {USD.symbol} - - - - - Docs - - + + {!isConnected && ( + + + + Show values in {USD.symbol} + + + Docs + + + )} + {/* TODO: Add animation to show activity bar */} + {isConnected && ( + <> + + {/* TODO: Handle click actions */} + + Show values in {USD.symbol} + + + + + Docs + + + + )} ({ body: { "--toast-z-index": 1410, + "#chakra-toast-manager-top": { + marginTop: "toast_container_shift !important", + }, // TODO: Update when the dark theme is ready backgroundColor: mode("gold.300", "gold.300")(props), color: mode("grey.700", "grey.700")(props), diff --git a/dapp/src/theme/utils/colors.ts b/dapp/src/theme/utils/colors.ts index b3c103d2a..14a77fc45 100644 --- a/dapp/src/theme/utils/colors.ts +++ b/dapp/src/theme/utils/colors.ts @@ -64,7 +64,8 @@ export const colors = { }, }, black: { - "15": "rgba(0, 0, 0, 0.15)", + "05": "rgba(0, 0, 0, 0.05)", + 15: "rgba(0, 0, 0, 0.15)", }, }, } diff --git a/dapp/src/theme/utils/semanticTokens.ts b/dapp/src/theme/utils/semanticTokens.ts index 8db4851c1..41879fe4d 100644 --- a/dapp/src/theme/utils/semanticTokens.ts +++ b/dapp/src/theme/utils/semanticTokens.ts @@ -2,6 +2,7 @@ export const semanticTokens = { space: { header_height: 24, modal_shift: 48, + toast_container_shift: 16, }, sizes: { sidebar_width: 80, diff --git a/dapp/src/utils/errors.ts b/dapp/src/utils/errors.ts index f8675aa55..091178332 100644 --- a/dapp/src/utils/errors.ts +++ b/dapp/src/utils/errors.ts @@ -1,4 +1,5 @@ export const ERRORS = { SIGNING: "Message signing error.", DEPOSIT_TRANSACTION: "Deposit transaction execution error.", + WALLET_NOT_CONNECTED: (type: string) => `${type} wallet is not connected.`, } From a84b69cae835e1eb3e6ec28f86ddbd5654e0edb8 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 13 Mar 2024 13:15:40 +0100 Subject: [PATCH 011/110] Create a separate directory for alerts --- .../ActiveStakingStep/DepositBTCModal.tsx | 3 +-- .../ActiveStakingStep/SignMessageModal.tsx | 3 +-- .../ActiveUnstakingStep/SignMessageModal.tsx | 2 +- .../ModalContentWrapper/MissingAccountModal.tsx | 2 +- .../ModalContentWrapper/SuccessModal.tsx | 2 +- dapp/src/components/shared/{ => alerts}/Alert.tsx | 2 +- dapp/src/components/shared/{ => alerts}/CardAlert.tsx | 4 ++-- .../shared/{ => alerts}/ReceiveSTBTCAlert.tsx | 6 +++--- dapp/src/components/shared/{ => alerts}/Toast.tsx | 11 +++-------- dapp/src/components/shared/alerts/index.tsx | 4 ++++ dapp/src/hooks/useWalletToast.tsx | 2 +- 11 files changed, 19 insertions(+), 22 deletions(-) rename dapp/src/components/shared/{ => alerts}/Alert.tsx (96%) rename dapp/src/components/shared/{ => alerts}/CardAlert.tsx (92%) rename dapp/src/components/shared/{ => alerts}/ReceiveSTBTCAlert.tsx (72%) rename dapp/src/components/shared/{ => alerts}/Toast.tsx (70%) create mode 100644 dapp/src/components/shared/alerts/index.tsx diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index 7c52ea051..c24c847b1 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -12,8 +12,7 @@ import { import { TextMd, TextSm } from "#/components/shared/Typography" import { ERRORS, logPromiseFailure } from "#/utils" import { PROCESS_STATUSES } from "#/types" -import CardAlert from "#/components/shared/CardAlert" -import Toast from "#/components/shared/Toast" +import { CardAlert, Toast } from "#/components/shared/alerts" import StakingStepsModalContent from "./StakingStepsModalContent" const ID_TOAST = "deposit-btc-error-toast" diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx index 8e0bd1c36..c631b38c7 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx @@ -7,9 +7,8 @@ import { } from "#/hooks" import { ERRORS, logPromiseFailure } from "#/utils" import { PROCESS_STATUSES } from "#/types" -import ReceiveSTBTCAlert from "#/components/shared/ReceiveSTBTCAlert" -import Toast from "#/components/shared/Toast" import { TextSm } from "#/components/shared/Typography" +import { ReceiveSTBTCAlert, Toast } from "#/components/shared/alerts" import StakingStepsModalContent from "./StakingStepsModalContent" const ID_TOAST = "sign-message-error-toast" diff --git a/dapp/src/components/TransactionModal/ActiveUnstakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveUnstakingStep/SignMessageModal.tsx index 0828456f9..d462cab94 100644 --- a/dapp/src/components/TransactionModal/ActiveUnstakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveUnstakingStep/SignMessageModal.tsx @@ -4,7 +4,7 @@ import { PROCESS_STATUSES } from "#/types" import { Button, ModalBody, ModalFooter, ModalHeader } from "@chakra-ui/react" import { TextMd } from "#/components/shared/Typography" import { logPromiseFailure } from "#/utils" -import ReceiveSTBTCAlert from "#/components/shared/ReceiveSTBTCAlert" +import { ReceiveSTBTCAlert } from "#/components/shared/alerts" export default function SignMessageModal() { const { setStatus } = useModalFlowContext() diff --git a/dapp/src/components/TransactionModal/ModalContentWrapper/MissingAccountModal.tsx b/dapp/src/components/TransactionModal/ModalContentWrapper/MissingAccountModal.tsx index 1be423c4b..e2c358152 100644 --- a/dapp/src/components/TransactionModal/ModalContentWrapper/MissingAccountModal.tsx +++ b/dapp/src/components/TransactionModal/ModalContentWrapper/MissingAccountModal.tsx @@ -11,7 +11,7 @@ import { import { TextMd } from "#/components/shared/Typography" import { logPromiseFailure, getCurrencyByType } from "#/utils" import { CurrencyType, RequestAccountParams } from "#/types" -import CardAlert from "#/components/shared/CardAlert" +import { CardAlert } from "#/components/shared/alerts" type MissingAccountModalProps = { currency: CurrencyType diff --git a/dapp/src/components/TransactionModal/ModalContentWrapper/SuccessModal.tsx b/dapp/src/components/TransactionModal/ModalContentWrapper/SuccessModal.tsx index 890e9cdff..e6dac590e 100644 --- a/dapp/src/components/TransactionModal/ModalContentWrapper/SuccessModal.tsx +++ b/dapp/src/components/TransactionModal/ModalContentWrapper/SuccessModal.tsx @@ -11,7 +11,7 @@ import { LoadingSpinnerSuccessIcon } from "#/assets/icons" import { useModalFlowContext } from "#/hooks" import { CurrencyBalanceWithConversion } from "#/components/shared/CurrencyBalanceWithConversion" import { ACTION_FLOW_TYPES, ActionFlowType, TokenAmount } from "#/types" -import ReceiveSTBTCAlert from "#/components/shared/ReceiveSTBTCAlert" +import { ReceiveSTBTCAlert } from "#/components/shared/alerts" const HEADER = { [ACTION_FLOW_TYPES.STAKE]: "Staking successful!", diff --git a/dapp/src/components/shared/Alert.tsx b/dapp/src/components/shared/alerts/Alert.tsx similarity index 96% rename from dapp/src/components/shared/Alert.tsx rename to dapp/src/components/shared/alerts/Alert.tsx index a18deb1c3..78ed33de3 100644 --- a/dapp/src/components/shared/Alert.tsx +++ b/dapp/src/components/shared/alerts/Alert.tsx @@ -25,7 +25,7 @@ export type AlertProps = ChakraAlertProps & { onClose?: () => void } -export default function Alert({ +export function Alert({ status = "info", alertIconColor, withAlertIcon, diff --git a/dapp/src/components/shared/CardAlert.tsx b/dapp/src/components/shared/alerts/CardAlert.tsx similarity index 92% rename from dapp/src/components/shared/CardAlert.tsx rename to dapp/src/components/shared/alerts/CardAlert.tsx index 56314fb60..2f5de52b1 100644 --- a/dapp/src/components/shared/CardAlert.tsx +++ b/dapp/src/components/shared/alerts/CardAlert.tsx @@ -1,14 +1,14 @@ import React from "react" import { HStack, Flex } from "@chakra-ui/react" import { ArrowUpRight } from "#/assets/icons" -import Alert, { AlertProps } from "./Alert" +import { Alert, AlertProps } from "./Alert" export type CardAlertProps = { withLink?: boolean onclick?: () => void } & Omit -export default function CardAlert({ +export function CardAlert({ withLink = false, children, onclick, diff --git a/dapp/src/components/shared/ReceiveSTBTCAlert.tsx b/dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx similarity index 72% rename from dapp/src/components/shared/ReceiveSTBTCAlert.tsx rename to dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx index 3897ff2ab..bf3fabbfb 100644 --- a/dapp/src/components/shared/ReceiveSTBTCAlert.tsx +++ b/dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx @@ -1,9 +1,9 @@ import React from "react" import { Highlight } from "@chakra-ui/react" -import { TextMd } from "#/components/shared/Typography" -import CardAlert, { CardAlertProps } from "./CardAlert" +import { CardAlert, CardAlertProps } from "./CardAlert" +import { TextMd } from "../Typography" -export default function ReceiveSTBTCAlert({ ...restProps }: CardAlertProps) { +export function ReceiveSTBTCAlert({ ...restProps }: CardAlertProps) { return ( // TODO: Add the correct action after click {}} {...restProps}> diff --git a/dapp/src/components/shared/Toast.tsx b/dapp/src/components/shared/alerts/Toast.tsx similarity index 70% rename from dapp/src/components/shared/Toast.tsx rename to dapp/src/components/shared/alerts/Toast.tsx index 0f97a6ba6..89d07438c 100644 --- a/dapp/src/components/shared/Toast.tsx +++ b/dapp/src/components/shared/alerts/Toast.tsx @@ -1,7 +1,7 @@ import React from "react" import { HStack } from "@chakra-ui/react" -import { TextSm } from "./Typography" -import Alert, { AlertProps } from "./Alert" +import { Alert, AlertProps } from "./Alert" +import { TextSm } from "../Typography" type ToastProps = { title: string @@ -9,12 +9,7 @@ type ToastProps = { onClose: () => void } -export default function Toast({ - title, - children, - onClose, - ...props -}: ToastProps) { +export function Toast({ title, children, onClose, ...props }: ToastProps) { return ( diff --git a/dapp/src/components/shared/alerts/index.tsx b/dapp/src/components/shared/alerts/index.tsx new file mode 100644 index 000000000..ae4273f89 --- /dev/null +++ b/dapp/src/components/shared/alerts/index.tsx @@ -0,0 +1,4 @@ +export * from "./Alert" +export * from "./CardAlert" +export * from "./ReceiveSTBTCAlert" +export * from "./Toast" diff --git a/dapp/src/hooks/useWalletToast.tsx b/dapp/src/hooks/useWalletToast.tsx index 4507cb92c..98fa60837 100644 --- a/dapp/src/hooks/useWalletToast.tsx +++ b/dapp/src/hooks/useWalletToast.tsx @@ -1,8 +1,8 @@ import React, { useCallback, useEffect, useState } from "react" import { ONE_SEC_IN_MILLISECONDS } from "#/constants" -import Toast from "#/components/shared/Toast" import { ERRORS, capitalize, logPromiseFailure } from "#/utils" import { Button, Flex } from "@chakra-ui/react" +import { Toast } from "#/components/shared/alerts" import { useToast } from "./useToast" import { useWallet } from "./useWallet" From 166dac971bd24625dc9bc7653914e84f5bffa104 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Thu, 14 Mar 2024 14:05:24 +0100 Subject: [PATCH 012/110] Group the staking fees by networks We want to group the staking fees by tBTC and Acre networks. --- sdk/src/lib/contracts/bitcoin-depositor.ts | 22 +++++++++- sdk/src/lib/ethereum/bitcoin-depositor.ts | 17 +++++--- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 42 +++++++++++--------- 3 files changed, 55 insertions(+), 26 deletions(-) diff --git a/sdk/src/lib/contracts/bitcoin-depositor.ts b/sdk/src/lib/contracts/bitcoin-depositor.ts index 58fdc8e61..3e1120dd5 100644 --- a/sdk/src/lib/contracts/bitcoin-depositor.ts +++ b/sdk/src/lib/contracts/bitcoin-depositor.ts @@ -9,7 +9,10 @@ export type DecodedExtraData = { referral: number } -export type StakingFees = { +/** + * Represents the tBTC network minting fees. + */ +type TBTCMintingFees = { /** * The tBTC treasury fee taken from each deposit and transferred to the * treasury upon sweep proof submission. Is calculated based on the initial @@ -27,6 +30,12 @@ export type StakingFees = { * transaction. */ depositTxMaxFee: bigint +} + +/** + * Represents the Acre network staking fees. + */ +type AcreStakingFees = { /** * The Acre network depositor fee taken from each deposit and transferred to * the treasury upon stake request finalization. @@ -34,6 +43,11 @@ export type StakingFees = { depositorFee: bigint } +export type StakingFees = { + tbtc: TBTCMintingFees + acre: AcreStakingFees +} + /** * Interface for communication with the AcreBitcoinDepositor on-chain contract. */ @@ -61,5 +75,11 @@ export interface BitcoinDepositor extends DepositorProxy { */ decodeExtraData(extraData: string): DecodedExtraData + /** + * Estimates the staking fees based on the provided amount. + * @param amountToStake Amount to stake in 1e8 satoshi precision. + * @returns Staking fees grouped by tBTC and Acre networks in 1e18 tBTC token + * precision. + */ estimateStakingFees(amountToStake: bigint): Promise } diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index 7d6c7d594..f512461b7 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -145,6 +145,9 @@ class EthereumBitcoinDepositor return { staker, referral } } + /** + * @see {BitcoinDepositor#estimateStakingFees} + */ async estimateStakingFees(amountToStake: bigint): Promise { const { depositTreasuryFeeDivisor, depositTxMaxFee } = await this.#getTbtcDepositParameters() @@ -171,13 +174,15 @@ class EthereumBitcoinDepositor ? (amountToStake * this.#satoshiMultiplier) / depositorFeeDivisor : 0n - // TODO: Maybe we should group fees by network? Eg.: - // `const fess = { tbtc: {...}, acre: {...}}` return { - treasuryFee: treasuryFee * this.#satoshiMultiplier, - optimisticMintingFee, - depositTxMaxFee: depositTxMaxFee * this.#satoshiMultiplier, - depositorFee, + tbtc: { + treasuryFee: treasuryFee * this.#satoshiMultiplier, + optimisticMintingFee, + depositTxMaxFee: depositTxMaxFee * this.#satoshiMultiplier, + }, + acre: { + depositorFee, + }, } } diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index 93545b3f9..7ef9a6fe5 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -276,25 +276,29 @@ describe("BitcoinDepositor", () => { const amountToStake = 10_000_000n // 0.1 BTC const expectedResult = { - // The fee is calculated based on the initial funding - // transaction amount. `amountToStake / depositTreasuryFeeDivisor` - // 0.00005 tBTC in 1e18 precision. - treasuryFee: 50000000000000n, - // Maximum amount of BTC transaction fee that can - // be incurred by each swept deposit being part of the given sweep - // transaction. - // 0.001 tBTC in 1e18 precision. - depositTxMaxFee: 1000000000000000n, - // Divisor used to compute the depositor fee taken from each deposit - // and transferred to the treasury upon stake request finalization. - // `depositorFee = depositedAmount / depositorFeeDivisor` - // 0.0001 tBTC in 1e18 precision. - depositorFee: 100000000000000n, - // The optimistic fee is a percentage AFTER - // the treasury fee is cut: - // `fee = (depositAmount - treasuryFee) / optimisticMintingFeeDivisor` - // 0.0001999 tBTC in 1e18 precision. - optimisticMintingFee: 199900000000000n, + tbtc: { + // The fee is calculated based on the initial funding + // transaction amount. `amountToStake / depositTreasuryFeeDivisor` + // 0.00005 tBTC in 1e18 precision. + treasuryFee: 50000000000000n, + // Maximum amount of BTC transaction fee that can + // be incurred by each swept deposit being part of the given sweep + // transaction. + // 0.001 tBTC in 1e18 precision. + depositTxMaxFee: 1000000000000000n, + // The optimistic fee is a percentage AFTER + // the treasury fee is cut: + // `fee = (depositAmount - treasuryFee) / optimisticMintingFeeDivisor` + // 0.0001999 tBTC in 1e18 precision. + optimisticMintingFee: 199900000000000n, + }, + acre: { + // Divisor used to compute the depositor fee taken from each deposit + // and transferred to the treasury upon stake request finalization. + // `depositorFee = depositedAmount / depositorFeeDivisor` + // 0.0001 tBTC in 1e18 precision. + depositorFee: 100000000000000n, + }, } beforeAll(() => { From a16ae3c1a2fce767f7dec99cfc6c6d657c3f23f4 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Thu, 14 Mar 2024 14:57:23 +0100 Subject: [PATCH 013/110] Export useful functions from useToast --- .../ActiveStakingStep/DepositBTCModal.tsx | 17 +++++------- .../ActiveStakingStep/SignMessageModal.tsx | 17 +++--------- dapp/src/hooks/useToast.ts | 26 ++++++++++++++++--- dapp/src/hooks/useWalletToast.tsx | 13 +++------- 4 files changed, 37 insertions(+), 36 deletions(-) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index c24c847b1..7450638df 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -1,4 +1,4 @@ -import React, { useCallback } from "react" +import React, { useCallback, useEffect } from "react" import { useDepositBTCTransaction, useDepositTelemetry, @@ -15,8 +15,6 @@ import { PROCESS_STATUSES } from "#/types" import { CardAlert, Toast } from "#/components/shared/alerts" import StakingStepsModalContent from "./StakingStepsModalContent" -const ID_TOAST = "deposit-btc-error-toast" - export default function DepositBTCModal() { const { ethAccount } = useWalletContext() const { tokenAmount } = useTransactionContext() @@ -24,7 +22,8 @@ export default function DepositBTCModal() { const { btcAddress, depositReceipt, stake } = useStakeFlowContext() const depositTelemetry = useDepositTelemetry() - const toast = useToast({ + const { closeToast, showToast } = useToast({ + id: "deposit-btc-error-toast", render: ({ onClose }) => ( () => closeToast(), [closeToast]) + const onStakeBTCSuccess = useCallback(() => { setStatus(PROCESS_STATUSES.SUCCEEDED) }, [setStatus]) @@ -61,13 +62,7 @@ export default function DepositBTCModal() { }, 10000) }, [setStatus, handleStake]) - const onDepositBTCError = useCallback(() => { - if (!toast.isActive(ID_TOAST)) { - toast({ - id: ID_TOAST, - }) - } - }, [toast]) + const onDepositBTCError = useCallback(showToast, [showToast]) const { sendBitcoinTransaction } = useDepositBTCTransaction( onDepositBTCSuccess, diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx index c631b38c7..054fef238 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx @@ -11,13 +11,12 @@ import { TextSm } from "#/components/shared/Typography" import { ReceiveSTBTCAlert, Toast } from "#/components/shared/alerts" import StakingStepsModalContent from "./StakingStepsModalContent" -const ID_TOAST = "sign-message-error-toast" - export default function SignMessageModal() { const { goNext, setStatus } = useModalFlowContext() const { signMessage } = useStakeFlowContext() - const toast = useToast({ + const { closeToast, showToast } = useToast({ + id: "sign-message-error-toast", render: ({ onClose }) => ( Please try again. @@ -25,15 +24,7 @@ export default function SignMessageModal() { ), }) - const onError = useCallback(() => { - if (!toast.isActive(ID_TOAST)) { - toast({ - id: ID_TOAST, - }) - } - }, [toast]) - - const handleSignMessage = useExecuteFunction(signMessage, goNext, onError) + const handleSignMessage = useExecuteFunction(signMessage, goNext, showToast) const handleSignMessageWrapper = useCallback(() => { logPromiseFailure(handleSignMessage()) @@ -43,7 +34,7 @@ export default function SignMessageModal() { setStatus(PROCESS_STATUSES.PENDING) }, [setStatus]) - useEffect(() => () => toast.close(ID_TOAST), [toast]) + useEffect(() => () => closeToast(), [closeToast]) return ( & { id: ToastId }) { + const toast = useChakraToast({ position: "top", duration: null, isClosable: true, containerStyle: { my: 1 }, ...props, }) + + const showToast = useCallback(() => { + if (!toast.isActive(id)) { + toast({ + id, + }) + } + }, [id, toast]) + + const closeToast = useCallback(() => toast.close(id), [id, toast]) + + return { toast, showToast, closeToast } } diff --git a/dapp/src/hooks/useWalletToast.tsx b/dapp/src/hooks/useWalletToast.tsx index 98fa60837..086196edd 100644 --- a/dapp/src/hooks/useWalletToast.tsx +++ b/dapp/src/hooks/useWalletToast.tsx @@ -21,7 +21,8 @@ export function useWalletToast( [requestAccount], ) - const toast = useToast({ + const { closeToast, showToast } = useToast({ + id: `${type}-account-toast`, render: ({ onClose }) => ( { - if (!toast.isActive(type)) { - toast({ id: type }) - } - }, [toast, type]) - useEffect(() => { if (isToastClosed) return @@ -64,7 +59,7 @@ export function useWalletToast( useEffect(() => { if (!account || isToastClosed) return - toast.close(type) + closeToast() setIsToastClosed(true) - }, [account, isToastClosed, toast, type]) + }, [account, closeToast, isToastClosed, type]) } From a4a22f2dec1ded427efe555c8f56479274c5a4ce Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Thu, 14 Mar 2024 15:20:24 +0100 Subject: [PATCH 014/110] Show button loading status when deposit address is verifying --- .../ActiveStakingStep/DepositBTCModal.tsx | 8 ++++++-- .../StakingStepsModalContent.tsx | 20 ++++++++++--------- .../shared/Form/FormSubmitButton.tsx | 15 ++++---------- dapp/src/components/shared/LoadingButton.tsx | 20 +++++++++++++++++++ 4 files changed, 41 insertions(+), 22 deletions(-) create mode 100644 dapp/src/components/shared/LoadingButton.tsx diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index 7450638df..7c7c9e892 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect } from "react" +import React, { useCallback, useEffect, useState } from "react" import { useDepositBTCTransaction, useDepositTelemetry, @@ -22,6 +22,8 @@ export default function DepositBTCModal() { const { btcAddress, depositReceipt, stake } = useStakeFlowContext() const depositTelemetry = useDepositTelemetry() + const [isLoading, setIsLoading] = useState(false) + const { closeToast, showToast } = useToast({ id: "deposit-btc-error-toast", render: ({ onClose }) => ( @@ -73,12 +75,13 @@ export default function DepositBTCModal() { if (!tokenAmount?.amount || !btcAddress || !depositReceipt || !ethAccount) return + setIsLoading(true) const response = await depositTelemetry( depositReceipt, btcAddress, ethAccount.address, ) - + setIsLoading(false) // TODO: Display the correct message for the user if (response.verificationStatus !== "valid") return @@ -100,6 +103,7 @@ export default function DepositBTCModal() { diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/StakingStepsModalContent.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/StakingStepsModalContent.tsx index bca9915d2..24f13b273 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/StakingStepsModalContent.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/StakingStepsModalContent.tsx @@ -1,14 +1,9 @@ import React from "react" -import { - Button, - HStack, - ModalBody, - ModalFooter, - ModalHeader, -} from "@chakra-ui/react" +import { HStack, ModalBody, ModalFooter, ModalHeader } from "@chakra-ui/react" import { TextLg, TextMd } from "#/components/shared/Typography" import StepperBase, { StepBase } from "#/components/shared/StepperBase" import Spinner from "#/components/shared/Spinner" +import { LoadingButton } from "#/components/shared/LoadingButton" export function Title({ children }: { children: React.ReactNode }) { return {children} @@ -43,12 +38,14 @@ const STEPS: StepBase[] = [ export default function StakingStepsModalContent({ buttonText, + isLoading, activeStep, onClick, children, }: { buttonText: string activeStep: number + isLoading?: boolean onClick: () => void children: React.ReactNode }) { @@ -68,9 +65,14 @@ export default function StakingStepsModalContent({ {children} - + ) diff --git a/dapp/src/components/shared/Form/FormSubmitButton.tsx b/dapp/src/components/shared/Form/FormSubmitButton.tsx index 4991fddd6..d03fe4e25 100644 --- a/dapp/src/components/shared/Form/FormSubmitButton.tsx +++ b/dapp/src/components/shared/Form/FormSubmitButton.tsx @@ -1,27 +1,20 @@ import React from "react" import { useFormikContext } from "formik" -import { Button, ButtonProps } from "@chakra-ui/react" -import Spinner from "../Spinner" - -const LOADING_STYLE = { - _disabled: { background: "gold.300", opacity: 1 }, - _hover: { opacity: 1 }, -} +import { ButtonProps } from "@chakra-ui/react" +import { LoadingButton } from "../LoadingButton" export function FormSubmitButton({ children, ...props }: ButtonProps) { const { isSubmitting } = useFormikContext() return ( - + ) } diff --git a/dapp/src/components/shared/LoadingButton.tsx b/dapp/src/components/shared/LoadingButton.tsx new file mode 100644 index 000000000..2066c8b0d --- /dev/null +++ b/dapp/src/components/shared/LoadingButton.tsx @@ -0,0 +1,20 @@ +import React from "react" +import { Button, ButtonProps, Spinner } from "@chakra-ui/react" + +const LOADING_STYLE = { + _disabled: { background: "gold.300", opacity: 1 }, + _hover: { opacity: 1 }, +} + +export function LoadingButton({ isLoading, children, ...props }: ButtonProps) { + return ( + + ) +} From b56701455586932396c9ae7035b0c3193c023fda Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Thu, 14 Mar 2024 15:52:23 +0100 Subject: [PATCH 015/110] Expose the `estimateStakingFees` in staking module This function returns the staking fees estimated based on the provided amount grouped by tBTC and Acre network fees. Fees are in 1e8 satoshi precision. --- sdk/src/lib/utils/index.ts | 1 + sdk/src/lib/utils/satoshi-converter.ts | 11 ++++ sdk/src/modules/staking/index.ts | 26 +++++++- sdk/test/modules/staking.test.ts | 90 ++++++++++++++++++++++++++ 4 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 sdk/src/lib/utils/satoshi-converter.ts diff --git a/sdk/src/lib/utils/index.ts b/sdk/src/lib/utils/index.ts index 294cd1874..70c6b147c 100644 --- a/sdk/src/lib/utils/index.ts +++ b/sdk/src/lib/utils/index.ts @@ -1,3 +1,4 @@ export * from "./hex" export * from "./ethereum-signer" export * from "./backoff" +export * from "./satoshi-converter" diff --git a/sdk/src/lib/utils/satoshi-converter.ts b/sdk/src/lib/utils/satoshi-converter.ts new file mode 100644 index 000000000..8c43de3e2 --- /dev/null +++ b/sdk/src/lib/utils/satoshi-converter.ts @@ -0,0 +1,11 @@ +const BTC_DECIMALS = 8n + +// eslint-disable-next-line import/prefer-default-export +export function toSatoshi(amount: bigint, fromPrecision: bigint = 18n) { + const SATOSHI_MULTIPLIER = 10n ** (fromPrecision - BTC_DECIMALS) + + const remainder = amount % SATOSHI_MULTIPLIER + const satoshis = (amount - remainder) / SATOSHI_MULTIPLIER + + return satoshis +} diff --git a/sdk/src/modules/staking/index.ts b/sdk/src/modules/staking/index.ts index efea34584..23f9ae3ee 100644 --- a/sdk/src/modules/staking/index.ts +++ b/sdk/src/modules/staking/index.ts @@ -2,6 +2,7 @@ import { ChainIdentifier, TBTC } from "@keep-network/tbtc-v2.ts" import { AcreContracts, DepositorProxy, StakingFees } from "../../lib/contracts" import { ChainEIP712Signer } from "../../lib/eip712-signer" import { StakeInitialization } from "./stake-initialization" +import { toSatoshi } from "../../lib/utils" /** * Module exposing features related to the staking. @@ -79,8 +80,29 @@ class StakingModule { return this.#contracts.stBTC.assetsBalanceOf(identifier) } - estimateStakingFees(amount: bigint): Promise { - return this.#contracts.bitcoinDepositor.estimateStakingFees(amount) + /** + * Estimates the staking fees based on the provided amount. + * @param amountToStake Amount to stake in satoshi. + * @returns Staking fees grouped by tBTC and Acre networks in 1e8 satoshi + * precision. + */ + async estimateStakingFees(amount: bigint): Promise { + const { acre, tbtc } = + await this.#contracts.bitcoinDepositor.estimateStakingFees(amount) + + const feesToSatoshi = ( + fees: T, + ) => + Object.entries(fees).reduce( + (reducer, [key, value]) => + Object.assign(reducer, { [key]: toSatoshi(value) }), + {} as T, + ) + + return { + tbtc: feesToSatoshi(tbtc), + acre: feesToSatoshi(acre), + } } } diff --git a/sdk/test/modules/staking.test.ts b/sdk/test/modules/staking.test.ts index 664e54767..ee76c9146 100644 --- a/sdk/test/modules/staking.test.ts +++ b/sdk/test/modules/staking.test.ts @@ -8,7 +8,9 @@ import { DepositorProxy, DepositReceipt, EthereumAddress, + StakingFees, } from "../../src" +import * as satoshiConverter from "../../src/lib/utils/satoshi-converter" import { MockAcreContracts } from "../utils/mock-acre-contracts" import { MockMessageSigner } from "../utils/mock-message-signer" import { MockTBTC } from "../utils/mock-tbtc" @@ -21,6 +23,11 @@ const stakingModuleData: { bitcoinRecoveryAddress: string mockedDepositBTCAddress: string } + estimateStakingFees: { + amount: bigint + mockedStakingFees: StakingFees + expectedStakingFeesInSatoshi: StakingFees + } } = { initializeStake: { staker: EthereumAddress.from(ethers.Wallet.createRandom().address), @@ -32,6 +39,37 @@ const stakingModuleData: { mockedDepositBTCAddress: "tb1qma629cu92skg0t86lftyaf9uflzwhp7jk63h6mpmv3ezh6puvdhs6w2r05", }, + estimateStakingFees: { + amount: 10_000_000n, // 0.1 BTC + mockedStakingFees: { + tbtc: { + // 0.00005 tBTC in 1e18 precision. + treasuryFee: 50000000000000n, + // 0.001 tBTC in 1e18 precision. + depositTxMaxFee: 1000000000000000n, + // 0.0001999 tBTC in 1e18 precision. + optimisticMintingFee: 199900000000000n, + }, + acre: { + // 0.0001 tBTC in 1e18 precision. + depositorFee: 100000000000000n, + }, + }, + expectedStakingFeesInSatoshi: { + tbtc: { + // 0.00005 BTC in 1e8 satoshi precision. + treasuryFee: 5000n, + // 0.001 BTC in 1e8 satoshi precision. + depositTxMaxFee: 100000n, + // 0.0001999 BTC in 1e8 satoshi precision. + optimisticMintingFee: 19990n, + }, + acre: { + // 0.0001 BTC in 1e8 satoshi precision. + depositorFee: 10000n, + }, + }, + }, } const stakingInitializationData: { @@ -395,4 +433,56 @@ describe("Staking", () => { expect(result).toEqual(expectedResult) }) }) + + describe("estimateStakingFees", () => { + const { + estimateStakingFees: { + amount, + mockedStakingFees, + expectedStakingFeesInSatoshi, + }, + } = stakingModuleData + + let result: StakingFees + const spyOnToSatoshi = jest.spyOn(satoshiConverter, "toSatoshi") + + beforeAll(async () => { + contracts.bitcoinDepositor.estimateStakingFees = jest + .fn() + .mockResolvedValue(mockedStakingFees) + result = await staking.estimateStakingFees(amount) + }) + + it("should get the staking fees from Acre Bitcoin Depositor contract handle", () => { + expect( + contracts.bitcoinDepositor.estimateStakingFees, + ).toHaveBeenCalledWith(amount) + }) + + it("should convert tBTC network fees to satoshi", () => { + expect(spyOnToSatoshi).toHaveBeenNthCalledWith( + 1, + mockedStakingFees.tbtc.treasuryFee, + ) + expect(spyOnToSatoshi).toHaveBeenNthCalledWith( + 2, + mockedStakingFees.tbtc.depositTxMaxFee, + ) + expect(spyOnToSatoshi).toHaveBeenNthCalledWith( + 3, + mockedStakingFees.tbtc.optimisticMintingFee, + ) + }) + + it("should convert Acre network fees to satoshi", () => { + expect(spyOnToSatoshi).toHaveBeenNthCalledWith( + 4, + mockedStakingFees.acre.depositorFee, + ) + }) + + it("should return the staking fees in satoshi precision", () => { + expect(result).toMatchObject(expectedStakingFeesInSatoshi) + }) + }) }) From ac1c50b1dc5bd6124a86cc835e82cfb328e0d6a4 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Thu, 14 Mar 2024 15:56:42 +0100 Subject: [PATCH 016/110] Update `estimateStakingFees` Update the `estimateStakingFees` function in Ethereum implementation of the `BitcoinDepositor` contract handle - we want to check if the `depositTreasuryFeeDivisor` value is greater than zero before we do division operation. --- sdk/src/lib/ethereum/bitcoin-depositor.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index f512461b7..56a8da7fd 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -152,7 +152,10 @@ class EthereumBitcoinDepositor const { depositTreasuryFeeDivisor, depositTxMaxFee } = await this.#getTbtcDepositParameters() - const treasuryFee = amountToStake / depositTreasuryFeeDivisor + const treasuryFee = + depositTreasuryFeeDivisor > 0 + ? amountToStake / depositTreasuryFeeDivisor + : 0n // Both deposit amount and treasury fee are in the 1e8 satoshi precision. // We need to convert them to the 1e18 TBTC precision. From 657417961dc9495029f72a4b9006b23d41e7df05 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Thu, 14 Mar 2024 16:03:32 +0100 Subject: [PATCH 017/110] Update `estimateStakingFees` Ethereum function Move all the contract parameters getters to the beginning of the `estimateStakingFees` function to improve readability. --- sdk/src/lib/ethereum/bitcoin-depositor.ts | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index 56a8da7fd..ea327a023 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -149,8 +149,11 @@ class EthereumBitcoinDepositor * @see {BitcoinDepositor#estimateStakingFees} */ async estimateStakingFees(amountToStake: bigint): Promise { - const { depositTreasuryFeeDivisor, depositTxMaxFee } = - await this.#getTbtcDepositParameters() + const { + depositTreasuryFeeDivisor, + depositTxMaxFee, + optimisticMintingFeeDivisor, + } = await this.#getTbtcMintingFeesParameters() const treasuryFee = depositTreasuryFeeDivisor > 0 @@ -162,8 +165,6 @@ class EthereumBitcoinDepositor const amountSubTreasury = (amountToStake - treasuryFee) * this.#satoshiMultiplier - const optimisticMintingFeeDivisor = - await this.#getTbtcOptimisticMintingFeeDivisor() const optimisticMintingFee = optimisticMintingFeeDivisor > 0 ? amountSubTreasury / optimisticMintingFeeDivisor @@ -189,6 +190,19 @@ class EthereumBitcoinDepositor } } + async #getTbtcMintingFeesParameters(): Promise< + TbtcDepositParameters & { optimisticMintingFeeDivisor: bigint } + > { + const depositParameters = await this.#getTbtcDepositParameters() + const optimisticMintingFeeDivisor = + await this.#getTbtcOptimisticMintingFeeDivisor() + + return { + ...depositParameters, + optimisticMintingFeeDivisor, + } + } + async #getTbtcDepositParameters(): Promise { if (this.#tbtcBridgeDepositsParameters) { return this.#tbtcBridgeDepositsParameters From cb68d46e57a11bacfd5c0441fe8ab086c9a897fd Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Fri, 15 Mar 2024 09:11:20 +0100 Subject: [PATCH 018/110] Show error notification when the execution of a deposit transaction is interrupted --- .../ActiveStakingStep/DepositBTCModal.tsx | 21 ++++++++++++------- dapp/src/hooks/useDepositBTCTransaction.ts | 11 +++++++++- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index 55cf36a58..a5920f9ff 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -39,9 +39,10 @@ export default function DepositBTCModal() { useEffect(() => () => closeToast(), [closeToast]) - const onStakeBTCSuccess = useCallback(() => { - setStatus(PROCESS_STATUSES.SUCCEEDED) - }, [setStatus]) + const onStakeBTCSuccess = useCallback( + () => setStatus(PROCESS_STATUSES.SUCCEEDED), + [setStatus], + ) // TODO: After a failed attempt, we should display the message const onStakeBTCError = useCallback(() => { @@ -60,7 +61,10 @@ export default function DepositBTCModal() { logPromiseFailure(handleStake()) }, [setStatus, handleStake]) - const onDepositBTCError = useCallback(showToast, [showToast]) + const onDepositBTCError = useCallback( + () => setTimeout(showToast, 100), + [showToast], + ) const { sendBitcoinTransaction } = useDepositBTCTransaction( onDepositBTCSuccess, @@ -78,16 +82,19 @@ export default function DepositBTCModal() { ethAccount.address, ) setIsLoading(false) - // TODO: Display the correct message for the user - if (response.verificationStatus !== "valid") return - logPromiseFailure(sendBitcoinTransaction(tokenAmount?.amount, btcAddress)) + if (response.verificationStatus === "valid") { + logPromiseFailure(sendBitcoinTransaction(tokenAmount?.amount, btcAddress)) + } else { + setTimeout(showToast, 100) + } }, [ btcAddress, depositReceipt, depositTelemetry, ethAccount, sendBitcoinTransaction, + showToast, tokenAmount?.amount, ]) diff --git a/dapp/src/hooks/useDepositBTCTransaction.ts b/dapp/src/hooks/useDepositBTCTransaction.ts index d0296298a..f256255d2 100644 --- a/dapp/src/hooks/useDepositBTCTransaction.ts +++ b/dapp/src/hooks/useDepositBTCTransaction.ts @@ -63,10 +63,19 @@ export function useDepositBTCTransaction( await signAndBroadcastTransaction(btcAccount.id, bitcoinTransaction) walletApiReactTransport.disconnect() } catch (e) { + if (onError) { + onError(error) + } console.error(e) } }, - [btcAccount, signAndBroadcastTransaction, walletApiReactTransport], + [ + btcAccount, + error, + onError, + signAndBroadcastTransaction, + walletApiReactTransport, + ], ) return { ...rest, sendBitcoinTransaction, transactionHash, error } From aa8113ef3364034f95916d0b428915317f37c680 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Fri, 15 Mar 2024 09:13:07 +0100 Subject: [PATCH 019/110] Update of error texts for dApp --- dapp/src/utils/errors.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dapp/src/utils/errors.ts b/dapp/src/utils/errors.ts index 091178332..26fa269fd 100644 --- a/dapp/src/utils/errors.ts +++ b/dapp/src/utils/errors.ts @@ -1,5 +1,5 @@ export const ERRORS = { - SIGNING: "Message signing error.", - DEPOSIT_TRANSACTION: "Deposit transaction execution error.", + SIGNING: "Message signing interrupted.", + DEPOSIT_TRANSACTION: "Deposit transaction execution interrupted.", WALLET_NOT_CONNECTED: (type: string) => `${type} wallet is not connected.`, } From 59e3432a03e8aedb314c839b751485ab4e58634e Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Fri, 15 Mar 2024 11:16:40 +0100 Subject: [PATCH 020/110] Simplify error handling logic for staking flow --- .../ActiveStakingStep/DepositBTCModal.tsx | 24 +++++++------- .../ActiveStakingStep/SignMessageModal.tsx | 32 +++++++++++++------ .../ModalContentWrapper/ResumeModal.tsx | 10 +++++- dapp/src/hooks/useToast.ts | 16 +++++++--- 4 files changed, 57 insertions(+), 25 deletions(-) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index a5920f9ff..8db51881b 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useState } from "react" +import React, { useCallback, useState } from "react" import { useDepositBTCTransaction, useDepositTelemetry, @@ -23,6 +23,7 @@ export default function DepositBTCModal() { const depositTelemetry = useDepositTelemetry() const [isLoading, setIsLoading] = useState(false) + const [buttonText, setButtonText] = useState("Deposit BTC") const { closeToast, showToast } = useToast({ id: "deposit-btc-error-toast", @@ -37,8 +38,6 @@ export default function DepositBTCModal() { ), }) - useEffect(() => () => closeToast(), [closeToast]) - const onStakeBTCSuccess = useCallback( () => setStatus(PROCESS_STATUSES.SUCCEEDED), [setStatus], @@ -56,15 +55,18 @@ export default function DepositBTCModal() { ) const onDepositBTCSuccess = useCallback(() => { + closeToast() setStatus(PROCESS_STATUSES.LOADING) logPromiseFailure(handleStake()) - }, [setStatus, handleStake]) + }, [closeToast, setStatus, handleStake]) - const onDepositBTCError = useCallback( - () => setTimeout(showToast, 100), - [showToast], - ) + const showError = useCallback(() => { + showToast() + setButtonText("Try again") + }, [showToast]) + + const onDepositBTCError = useCallback(() => showError(), [showError]) const { sendBitcoinTransaction } = useDepositBTCTransaction( onDepositBTCSuccess, @@ -86,7 +88,7 @@ export default function DepositBTCModal() { if (response.verificationStatus === "valid") { logPromiseFailure(sendBitcoinTransaction(tokenAmount?.amount, btcAddress)) } else { - setTimeout(showToast, 100) + showError() } }, [ btcAddress, @@ -94,7 +96,7 @@ export default function DepositBTCModal() { depositTelemetry, ethAccount, sendBitcoinTransaction, - showToast, + showError, tokenAmount?.amount, ]) @@ -104,7 +106,7 @@ export default function DepositBTCModal() { return ( { + setStatus(PROCESS_STATUSES.PENDING) + }, [setStatus]) const { closeToast, showToast } = useToast({ id: "sign-message-error-toast", @@ -24,21 +30,29 @@ export default function SignMessageModal() { ), }) - const handleSignMessage = useExecuteFunction(signMessage, goNext, showToast) + const onSignMessageSuccess = useCallback(() => { + closeToast() + goNext() + }, [closeToast, goNext]) + + const onSignMessageError = useCallback(() => { + showToast() + setButtonText("Try again") + }, [showToast]) + + const handleSignMessage = useExecuteFunction( + signMessage, + onSignMessageSuccess, + onSignMessageError, + ) const handleSignMessageWrapper = useCallback(() => { logPromiseFailure(handleSignMessage()) }, [handleSignMessage]) - useEffect(() => { - setStatus(PROCESS_STATUSES.PENDING) - }, [setStatus]) - - useEffect(() => () => closeToast(), [closeToast]) - return ( diff --git a/dapp/src/components/TransactionModal/ModalContentWrapper/ResumeModal.tsx b/dapp/src/components/TransactionModal/ModalContentWrapper/ResumeModal.tsx index fb633e7eb..fcedd61a8 100644 --- a/dapp/src/components/TransactionModal/ModalContentWrapper/ResumeModal.tsx +++ b/dapp/src/components/TransactionModal/ModalContentWrapper/ResumeModal.tsx @@ -1,10 +1,11 @@ -import React from "react" +import React, { useEffect } from "react" import { ModalHeader, ModalBody, ModalFooter, Button, HStack, + useToast, } from "@chakra-ui/react" import Spinner from "#/components/shared/Spinner" @@ -18,6 +19,13 @@ export default function ResumeModal({ onResume: () => void onClose: () => void }) { + const toast = useToast() + + useEffect(() => { + // All notifications should be closed when the user is in the resume modal. + toast.closeAll() + }, [toast]) + return ( <> Paused diff --git a/dapp/src/hooks/useToast.ts b/dapp/src/hooks/useToast.ts index 263223c3b..e91567cbd 100644 --- a/dapp/src/hooks/useToast.ts +++ b/dapp/src/hooks/useToast.ts @@ -19,13 +19,21 @@ export function useToast({ const showToast = useCallback(() => { if (!toast.isActive(id)) { - toast({ - id, - }) + setTimeout( + () => + toast({ + id, + }), + 100, + ) } }, [id, toast]) - const closeToast = useCallback(() => toast.close(id), [id, toast]) + const closeToast = useCallback(() => { + if (toast.isActive(id)) { + toast.close(id) + } + }, [id, toast]) return { toast, showToast, closeToast } } From 3bf2a6828f7d1b1a03082854b77c5477ea542a56 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Fri, 15 Mar 2024 11:42:33 +0100 Subject: [PATCH 021/110] Small improvements --- .../ActiveStakingStep/DepositBTCModal.tsx | 6 +--- .../ActiveStakingStep/SignMessageModal.tsx | 3 +- dapp/src/components/shared/alerts/Alert.tsx | 14 ++++---- .../components/shared/alerts/CardAlert.tsx | 4 +-- dapp/src/components/shared/alerts/Toast.tsx | 4 +-- dapp/src/hooks/useWalletToast.tsx | 1 - dapp/src/pages/OverviewPage/index.tsx | 36 ++++++++----------- 7 files changed, 28 insertions(+), 40 deletions(-) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index 8db51881b..b67c9e43a 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -28,11 +28,7 @@ export default function DepositBTCModal() { const { closeToast, showToast } = useToast({ id: "deposit-btc-error-toast", render: ({ onClose }) => ( - + Please try again. ), diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx index 8b7f316c1..d5066cbc1 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx @@ -1,4 +1,3 @@ -/* eslint-disable arrow-body-style */ import React, { useCallback, useEffect, useState } from "react" import { useExecuteFunction, @@ -24,7 +23,7 @@ export default function SignMessageModal() { const { closeToast, showToast } = useToast({ id: "sign-message-error-toast", render: ({ onClose }) => ( - + Please try again. ), diff --git a/dapp/src/components/shared/alerts/Alert.tsx b/dapp/src/components/shared/alerts/Alert.tsx index 78ed33de3..7f06f2201 100644 --- a/dapp/src/components/shared/alerts/Alert.tsx +++ b/dapp/src/components/shared/alerts/Alert.tsx @@ -14,12 +14,12 @@ const ICONS = { error: AlertError, } -export type AlertStatus = keyof typeof ICONS +type AlertStatus = keyof typeof ICONS export type AlertProps = ChakraAlertProps & { status?: AlertStatus - alertIconColor?: string - withAlertIcon?: boolean + colorIcon?: string + withIcon?: boolean withCloseButton?: boolean icon?: typeof Icon onClose?: () => void @@ -27,8 +27,8 @@ export type AlertProps = ChakraAlertProps & { export function Alert({ status = "info", - alertIconColor, - withAlertIcon, + colorIcon, + withIcon, children, withCloseButton, onClose, @@ -36,8 +36,8 @@ export function Alert({ }: AlertProps) { return ( - {withAlertIcon && status && ( - + {withIcon && status && ( + )} {children} diff --git a/dapp/src/components/shared/alerts/CardAlert.tsx b/dapp/src/components/shared/alerts/CardAlert.tsx index 2f5de52b1..6d242753d 100644 --- a/dapp/src/components/shared/alerts/CardAlert.tsx +++ b/dapp/src/components/shared/alerts/CardAlert.tsx @@ -22,8 +22,8 @@ export function CardAlert({ boxShadow="none" status="info" color="grey.700" - alertIconColor="grey.700" - withAlertIcon + colorIcon="grey.700" + withIcon {...props} > diff --git a/dapp/src/components/shared/alerts/Toast.tsx b/dapp/src/components/shared/alerts/Toast.tsx index 89d07438c..a43cc8519 100644 --- a/dapp/src/components/shared/alerts/Toast.tsx +++ b/dapp/src/components/shared/alerts/Toast.tsx @@ -5,13 +5,13 @@ import { TextSm } from "../Typography" type ToastProps = { title: string -} & Omit & { +} & Omit & { onClose: () => void } export function Toast({ title, children, onClose, ...props }: ToastProps) { return ( - + {title} {children} diff --git a/dapp/src/hooks/useWalletToast.tsx b/dapp/src/hooks/useWalletToast.tsx index 086196edd..bed9f7f24 100644 --- a/dapp/src/hooks/useWalletToast.tsx +++ b/dapp/src/hooks/useWalletToast.tsx @@ -25,7 +25,6 @@ export function useWalletToast( id: `${type}-account-toast`, render: ({ onClose }) => ( { diff --git a/dapp/src/pages/OverviewPage/index.tsx b/dapp/src/pages/OverviewPage/index.tsx index 5ec9fb351..444192776 100644 --- a/dapp/src/pages/OverviewPage/index.tsx +++ b/dapp/src/pages/OverviewPage/index.tsx @@ -15,32 +15,26 @@ export default function OverviewPage() { return ( - {!isConnected && ( - - - - Show values in {USD.symbol} - + + + {/* TODO: Handle click actions */} + + Show values in {USD.symbol} + + {!isConnected && ( Docs - - )} + )} + {/* TODO: Add animation to show activity bar */} {isConnected && ( - <> - - {/* TODO: Handle click actions */} - - Show values in {USD.symbol} - - - - - Docs - - - + + + + Docs + + )} Date: Fri, 15 Mar 2024 11:50:26 +0100 Subject: [PATCH 022/110] Rename from `isToastClosed` to `isToastAlreadyClosed` --- dapp/src/hooks/useWalletToast.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/dapp/src/hooks/useWalletToast.tsx b/dapp/src/hooks/useWalletToast.tsx index bed9f7f24..ccae7b21d 100644 --- a/dapp/src/hooks/useWalletToast.tsx +++ b/dapp/src/hooks/useWalletToast.tsx @@ -11,7 +11,7 @@ export function useWalletToast( delay = ONE_SEC_IN_MILLISECONDS, ) { // // The toast should be visible only once. - const [isToastClosed, setIsToastClosed] = useState(false) + const [isToastAlreadyClosed, setIsToastAlreadyClosed] = useState(false) const { [type]: { account, requestAccount }, } = useWallet() @@ -29,7 +29,7 @@ export function useWalletToast( title={ERRORS.WALLET_NOT_CONNECTED(capitalize(type))} onClose={() => { onClose() - setIsToastClosed(true) + setIsToastAlreadyClosed(true) }} > @@ -47,18 +47,18 @@ export function useWalletToast( }) useEffect(() => { - if (isToastClosed) return + if (isToastAlreadyClosed) return const timeout = setTimeout(showToast, delay) // eslint-disable-next-line consistent-return return () => clearTimeout(timeout) - }, [delay, isToastClosed, showToast]) + }, [delay, isToastAlreadyClosed, showToast]) useEffect(() => { - if (!account || isToastClosed) return + if (!account || isToastAlreadyClosed) return closeToast() - setIsToastClosed(true) - }, [account, closeToast, isToastClosed, type]) + setIsToastAlreadyClosed(true) + }, [account, closeToast, isToastAlreadyClosed, type]) } From 5c799df289902866fb4918429d2d95017bab060f Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Fri, 15 Mar 2024 16:19:00 +0100 Subject: [PATCH 023/110] Simplifying the logic of using toast component Created a custom useToast hook which wraps the useToast hook from Chakra UI and provides a render function to it to customize the toast components. In addition, a special ToastType was created to easily keep all kinds of notifications in the TOASTS object. This allows us to easily trigger a notification. Changing the approach of calling toast allowed to simplify the logic and get rid of unneeded parts of the code. --- .../ActiveStakingStep/DepositBTCModal.tsx | 26 +++---- .../ActiveStakingStep/SignMessageModal.tsx | 25 +++---- .../ModalContentWrapper/ResumeModal.tsx | 8 +-- dapp/src/components/shared/alerts/Toast.tsx | 70 ++++++++++++++++++- dapp/src/hooks/useToast.ts | 69 +++++++++--------- dapp/src/hooks/useWalletToast.ts | 50 +++++++++++++ dapp/src/hooks/useWalletToast.tsx | 64 ----------------- dapp/src/types/index.ts | 1 + dapp/src/types/toast.ts | 8 +++ dapp/src/utils/errors.ts | 5 -- dapp/src/utils/index.ts | 1 - 11 files changed, 186 insertions(+), 141 deletions(-) create mode 100644 dapp/src/hooks/useWalletToast.ts delete mode 100644 dapp/src/hooks/useWalletToast.tsx create mode 100644 dapp/src/types/toast.ts delete mode 100644 dapp/src/utils/errors.ts diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index b67c9e43a..61b1781b1 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -9,31 +9,25 @@ import { useTransactionContext, useWalletContext, } from "#/hooks" -import { TextMd, TextSm } from "#/components/shared/Typography" -import { ERRORS, logPromiseFailure } from "#/utils" -import { PROCESS_STATUSES } from "#/types" -import { CardAlert, Toast } from "#/components/shared/alerts" +import { TextMd } from "#/components/shared/Typography" +import { logPromiseFailure } from "#/utils" +import { PROCESS_STATUSES, TOAST_TYPES } from "#/types" +import { CardAlert, TOASTS } from "#/components/shared/alerts" import StakingStepsModalContent from "./StakingStepsModalContent" +const TOAST_ID = TOAST_TYPES.DEPOSIT_TRANSACTION_ERROR + export default function DepositBTCModal() { const { ethAccount } = useWalletContext() const { tokenAmount } = useTransactionContext() const { setStatus } = useModalFlowContext() const { btcAddress, depositReceipt, stake } = useStakeFlowContext() const depositTelemetry = useDepositTelemetry() + const { close: closeToast, open: openToast } = useToast() const [isLoading, setIsLoading] = useState(false) const [buttonText, setButtonText] = useState("Deposit BTC") - const { closeToast, showToast } = useToast({ - id: "deposit-btc-error-toast", - render: ({ onClose }) => ( - - Please try again. - - ), - }) - const onStakeBTCSuccess = useCallback( () => setStatus(PROCESS_STATUSES.SUCCEEDED), [setStatus], @@ -51,16 +45,16 @@ export default function DepositBTCModal() { ) const onDepositBTCSuccess = useCallback(() => { - closeToast() + closeToast(TOAST_ID) setStatus(PROCESS_STATUSES.LOADING) logPromiseFailure(handleStake()) }, [closeToast, setStatus, handleStake]) const showError = useCallback(() => { - showToast() + openToast(TOASTS[TOAST_ID]()) setButtonText("Try again") - }, [showToast]) + }, [openToast]) const onDepositBTCError = useCallback(() => showError(), [showError]) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx index d5066cbc1..345c4359e 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx @@ -5,39 +5,32 @@ import { useStakeFlowContext, useToast, } from "#/hooks" -import { ERRORS, logPromiseFailure } from "#/utils" -import { PROCESS_STATUSES } from "#/types" -import { TextSm } from "#/components/shared/Typography" -import { ReceiveSTBTCAlert, Toast } from "#/components/shared/alerts" +import { logPromiseFailure } from "#/utils" +import { PROCESS_STATUSES, TOAST_TYPES } from "#/types" +import { ReceiveSTBTCAlert, TOASTS } from "#/components/shared/alerts" import StakingStepsModalContent from "./StakingStepsModalContent" +const TOAST_ID = TOAST_TYPES.SIGNING_ERROR + export default function SignMessageModal() { const { goNext, setStatus } = useModalFlowContext() const { signMessage } = useStakeFlowContext() const [buttonText, setButtonText] = useState("Sign now") + const { close: closeToast, open: openToast } = useToast() useEffect(() => { setStatus(PROCESS_STATUSES.PENDING) }, [setStatus]) - const { closeToast, showToast } = useToast({ - id: "sign-message-error-toast", - render: ({ onClose }) => ( - - Please try again. - - ), - }) - const onSignMessageSuccess = useCallback(() => { - closeToast() + closeToast(TOAST_TYPES.SIGNING_ERROR) goNext() }, [closeToast, goNext]) const onSignMessageError = useCallback(() => { - showToast() + openToast(TOASTS[TOAST_ID]()) setButtonText("Try again") - }, [showToast]) + }, [openToast]) const handleSignMessage = useExecuteFunction( signMessage, diff --git a/dapp/src/components/TransactionModal/ModalContentWrapper/ResumeModal.tsx b/dapp/src/components/TransactionModal/ModalContentWrapper/ResumeModal.tsx index fcedd61a8..9e5bf6bd8 100644 --- a/dapp/src/components/TransactionModal/ModalContentWrapper/ResumeModal.tsx +++ b/dapp/src/components/TransactionModal/ModalContentWrapper/ResumeModal.tsx @@ -5,12 +5,12 @@ import { ModalFooter, Button, HStack, - useToast, } from "@chakra-ui/react" import Spinner from "#/components/shared/Spinner" import { PauseIcon } from "#/assets/icons" import { TextMd } from "#/components/shared/Typography" +import { useToast } from "#/hooks" export default function ResumeModal({ onResume, @@ -19,12 +19,12 @@ export default function ResumeModal({ onResume: () => void onClose: () => void }) { - const toast = useToast() + const { closeAll } = useToast() useEffect(() => { // All notifications should be closed when the user is in the resume modal. - toast.closeAll() - }, [toast]) + closeAll() + }, [closeAll]) return ( <> diff --git a/dapp/src/components/shared/alerts/Toast.tsx b/dapp/src/components/shared/alerts/Toast.tsx index a43cc8519..d97188ff3 100644 --- a/dapp/src/components/shared/alerts/Toast.tsx +++ b/dapp/src/components/shared/alerts/Toast.tsx @@ -1,5 +1,6 @@ import React from "react" -import { HStack } from "@chakra-ui/react" +import { Button, Flex, HStack, UseToastOptions } from "@chakra-ui/react" +import { TOAST_TYPES, ToastType } from "#/types" import { Alert, AlertProps } from "./Alert" import { TextSm } from "../Typography" @@ -19,3 +20,70 @@ export function Toast({ title, children, onClose, ...props }: ToastProps) { ) } + +export const TOASTS: Record< + ToastType, + (params?: { onClick: () => void }) => UseToastOptions +> = { + [TOAST_TYPES.BITCOIN_WALLET_NOT_CONNECTED_ERROR]: (params) => ({ + id: TOAST_TYPES.BITCOIN_WALLET_NOT_CONNECTED_ERROR, + render: ({ onClose }) => ( + onClose()} + > + + + + + ), + }), + [TOAST_TYPES.ETHEREUM_WALLET_NOT_CONNECTED_ERROR]: (params) => ({ + id: TOAST_TYPES.ETHEREUM_WALLET_NOT_CONNECTED_ERROR, + render: ({ onClose }) => ( + onClose()} + > + + + + + ), + }), + [TOAST_TYPES.SIGNING_ERROR]: () => ({ + id: TOAST_TYPES.SIGNING_ERROR, + render: ({ onClose }) => ( + + Please try again. + + ), + }), + [TOAST_TYPES.DEPOSIT_TRANSACTION_ERROR]: () => ({ + id: TOAST_TYPES.DEPOSIT_TRANSACTION_ERROR, + render: ({ onClose }) => ( + + Please try again. + + ), + }), +} diff --git a/dapp/src/hooks/useToast.ts b/dapp/src/hooks/useToast.ts index e91567cbd..97c469daf 100644 --- a/dapp/src/hooks/useToast.ts +++ b/dapp/src/hooks/useToast.ts @@ -1,39 +1,40 @@ -import { - ToastId, - UseToastOptions, - useToast as useChakraToast, -} from "@chakra-ui/react" -import { useCallback } from "react" +import { UseToastOptions, useToast as useChakraToast } from "@chakra-ui/react" +import { useCallback, useMemo } from "react" -export function useToast({ - id, - ...props -}: Omit & { id: ToastId }) { - const toast = useChakraToast({ - position: "top", - duration: null, - isClosable: true, - containerStyle: { my: 1 }, - ...props, - }) +export function useToast() { + const toast = useChakraToast() - const showToast = useCallback(() => { - if (!toast.isActive(id)) { - setTimeout( - () => - toast({ - id, - }), - 100, - ) - } - }, [id, toast]) + const returnFunction = useCallback( + (options: UseToastOptions) => + toast({ + position: "top", + duration: null, + isClosable: true, + containerStyle: { my: 1 }, + ...options, + }), + [toast], + ) - const closeToast = useCallback(() => { - if (toast.isActive(id)) { - toast.close(id) - } - }, [id, toast]) + const open = useCallback( + ({ id, ...options }: UseToastOptions) => { + if (!id) { + returnFunction(options) + } else if (!toast.isActive(id)) { + returnFunction({ + id, + ...options, + }) + } + }, + [returnFunction, toast], + ) - return { toast, showToast, closeToast } + return useMemo( + () => ({ + ...Object.assign(returnFunction, toast), + open, + }), + [returnFunction, toast, open], + ) } diff --git a/dapp/src/hooks/useWalletToast.ts b/dapp/src/hooks/useWalletToast.ts new file mode 100644 index 000000000..d8d024e20 --- /dev/null +++ b/dapp/src/hooks/useWalletToast.ts @@ -0,0 +1,50 @@ +import { useCallback, useEffect } from "react" +import { ONE_SEC_IN_MILLISECONDS } from "#/constants" +import { logPromiseFailure } from "#/utils" +import { TOASTS } from "#/components/shared/alerts" +import { TOAST_TYPES } from "#/types" +import { useToast } from "./useToast" +import { useWallet } from "./useWallet" + +const WALLET_TOAST = { + bitcoin: TOAST_TYPES.BITCOIN_WALLET_NOT_CONNECTED_ERROR, + ethereum: TOAST_TYPES.ETHEREUM_WALLET_NOT_CONNECTED_ERROR, +} + +export function useWalletToast( + type: "bitcoin" | "ethereum", + delay = ONE_SEC_IN_MILLISECONDS, +) { + const { + [type]: { account, requestAccount }, + } = useWallet() + const { close, open } = useToast() + + const toastId = WALLET_TOAST[type] + + const handleConnect = useCallback( + () => logPromiseFailure(requestAccount()), + [requestAccount], + ) + + useEffect(() => { + const timeout = setTimeout( + () => + open( + TOASTS[toastId]({ + onClick: handleConnect, + }), + ), + delay, + ) + + // eslint-disable-next-line consistent-return + return () => clearTimeout(timeout) + }, [delay, handleConnect, open, toastId, type]) + + useEffect(() => { + if (!account) return + + close(toastId) + }, [account, close, toastId]) +} diff --git a/dapp/src/hooks/useWalletToast.tsx b/dapp/src/hooks/useWalletToast.tsx deleted file mode 100644 index ccae7b21d..000000000 --- a/dapp/src/hooks/useWalletToast.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import React, { useCallback, useEffect, useState } from "react" -import { ONE_SEC_IN_MILLISECONDS } from "#/constants" -import { ERRORS, capitalize, logPromiseFailure } from "#/utils" -import { Button, Flex } from "@chakra-ui/react" -import { Toast } from "#/components/shared/alerts" -import { useToast } from "./useToast" -import { useWallet } from "./useWallet" - -export function useWalletToast( - type: "bitcoin" | "ethereum", - delay = ONE_SEC_IN_MILLISECONDS, -) { - // // The toast should be visible only once. - const [isToastAlreadyClosed, setIsToastAlreadyClosed] = useState(false) - const { - [type]: { account, requestAccount }, - } = useWallet() - - const handleConnect = useCallback( - () => logPromiseFailure(requestAccount()), - [requestAccount], - ) - - const { closeToast, showToast } = useToast({ - id: `${type}-account-toast`, - render: ({ onClose }) => ( - { - onClose() - setIsToastAlreadyClosed(true) - }} - > - - - - - ), - }) - - useEffect(() => { - if (isToastAlreadyClosed) return - - const timeout = setTimeout(showToast, delay) - - // eslint-disable-next-line consistent-return - return () => clearTimeout(timeout) - }, [delay, isToastAlreadyClosed, showToast]) - - useEffect(() => { - if (!account || isToastAlreadyClosed) return - - closeToast() - setIsToastAlreadyClosed(true) - }, [account, closeToast, isToastAlreadyClosed, type]) -} diff --git a/dapp/src/types/index.ts b/dapp/src/types/index.ts index 12a5dc7b3..652e02c2a 100644 --- a/dapp/src/types/index.ts +++ b/dapp/src/types/index.ts @@ -10,3 +10,4 @@ export * from "./location" export * from "./charts" export * from "./activity" export * from "./coingecko" +export * from "./toast" diff --git a/dapp/src/types/toast.ts b/dapp/src/types/toast.ts new file mode 100644 index 000000000..1202dd1a8 --- /dev/null +++ b/dapp/src/types/toast.ts @@ -0,0 +1,8 @@ +export const TOAST_TYPES = { + BITCOIN_WALLET_NOT_CONNECTED_ERROR: "bitcoin-wallet-error", + ETHEREUM_WALLET_NOT_CONNECTED_ERROR: "ethereum-wallet-error", + SIGNING_ERROR: "signing-error", + DEPOSIT_TRANSACTION_ERROR: "deposit-transaction-error", +} as const + +export type ToastType = (typeof TOAST_TYPES)[keyof typeof TOAST_TYPES] diff --git a/dapp/src/utils/errors.ts b/dapp/src/utils/errors.ts deleted file mode 100644 index 26fa269fd..000000000 --- a/dapp/src/utils/errors.ts +++ /dev/null @@ -1,5 +0,0 @@ -export const ERRORS = { - SIGNING: "Message signing interrupted.", - DEPOSIT_TRANSACTION: "Deposit transaction execution interrupted.", - WALLET_NOT_CONNECTED: (type: string) => `${type} wallet is not connected.`, -} diff --git a/dapp/src/utils/index.ts b/dapp/src/utils/index.ts index fd22154ed..cb7034c47 100644 --- a/dapp/src/utils/index.ts +++ b/dapp/src/utils/index.ts @@ -8,4 +8,3 @@ export * from "./time" export * from "./promise" export * from "./exchangeApi" export * from "./verifyDepositAddress" -export * from "./errors" From 2e9fa482d2d8acdf80135fea24834063fa25c4a7 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Mon, 18 Mar 2024 09:21:54 +0100 Subject: [PATCH 024/110] Use `TOAST_ID` everywhere to make the code transparent --- .../TransactionModal/ActiveStakingStep/SignMessageModal.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx index 345c4359e..3b7d6bb6b 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx @@ -23,7 +23,7 @@ export default function SignMessageModal() { }, [setStatus]) const onSignMessageSuccess = useCallback(() => { - closeToast(TOAST_TYPES.SIGNING_ERROR) + closeToast(TOAST_ID) goNext() }, [closeToast, goNext]) From d402e84e766c0a6957bbf66d5425c112bbc7424c Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Mon, 18 Mar 2024 10:20:13 +0100 Subject: [PATCH 025/110] Reorganize global styles for Chakra UI For edge cases, you will have to override the global styles for chakra components. I moved these styles to a separate file to keep things in order. This will also make it easy to use the zIndices or semanticTokens file. --- dapp/src/theme/index.ts | 26 ++++++++++---------------- dapp/src/theme/utils/index.ts | 1 + dapp/src/theme/utils/styles.ts | 28 ++++++++++++++++++++++++++++ dapp/src/theme/utils/zIndices.ts | 1 + 4 files changed, 40 insertions(+), 16 deletions(-) create mode 100644 dapp/src/theme/utils/styles.ts diff --git a/dapp/src/theme/index.ts b/dapp/src/theme/index.ts index 09268aa63..dd32c1970 100644 --- a/dapp/src/theme/index.ts +++ b/dapp/src/theme/index.ts @@ -1,8 +1,14 @@ -import { StyleFunctionProps, extendTheme } from "@chakra-ui/react" -import { mode } from "@chakra-ui/theme-tools" +import { extendTheme } from "@chakra-ui/react" import { buttonTheme } from "./Button" import { switchTheme } from "./Switch" -import { colors, fonts, lineHeights, semanticTokens, zIndices } from "./utils" +import { + colors, + fonts, + lineHeights, + semanticTokens, + styles, + zIndices, +} from "./utils" import { drawerTheme } from "./Drawer" import { modalTheme } from "./Modal" import { cardTheme } from "./Card" @@ -37,19 +43,7 @@ const defaultTheme = { lineHeights, zIndices, semanticTokens, - styles: { - global: (props: StyleFunctionProps) => ({ - body: { - "--toast-z-index": 1410, - "#chakra-toast-manager-top": { - marginTop: "toast_container_shift !important", - }, - // TODO: Update when the dark theme is ready - backgroundColor: mode("gold.300", "gold.300")(props), - color: mode("grey.700", "grey.700")(props), - }, - }), - }, + styles, components: { Alert: alertTheme, Button: buttonTheme, diff --git a/dapp/src/theme/utils/index.ts b/dapp/src/theme/utils/index.ts index d2fad7e05..d100be7bb 100644 --- a/dapp/src/theme/utils/index.ts +++ b/dapp/src/theme/utils/index.ts @@ -2,3 +2,4 @@ export * from "./colors" export * from "./fonts" export * from "./zIndices" export * from "./semanticTokens" +export * from "./styles" diff --git a/dapp/src/theme/utils/styles.ts b/dapp/src/theme/utils/styles.ts new file mode 100644 index 000000000..71be2dc70 --- /dev/null +++ b/dapp/src/theme/utils/styles.ts @@ -0,0 +1,28 @@ +import { StyleFunctionProps, defineStyle } from "@chakra-ui/react" +import { mode } from "@chakra-ui/theme-tools" +import { semanticTokens } from "./semanticTokens" +import { zIndices } from "./zIndices" + +const bodyStyle = defineStyle((props: StyleFunctionProps) => ({ + // TODO: Update when the dark theme is ready + backgroundColor: mode("gold.300", "gold.300")(props), + color: mode("grey.700", "grey.700")(props), +})) + +const toastManagerStyle = defineStyle({ + marginTop: `${semanticTokens.space.toast_container_shift} !important`, + // To set the correct z-index value for the toast component, + // we need to override it in the global styles + // More info: + // https://github.com/chakra-ui/chakra-ui/issues/7505 + zIndex: `${zIndices.toast} !important`, +}) + +const globalStyle = (props: StyleFunctionProps) => ({ + "#chakra-toast-manager-top": toastManagerStyle, + body: bodyStyle(props), +}) + +export const styles = { + global: (props: StyleFunctionProps) => globalStyle(props), +} diff --git a/dapp/src/theme/utils/zIndices.ts b/dapp/src/theme/utils/zIndices.ts index a0834c287..4f196f66f 100644 --- a/dapp/src/theme/utils/zIndices.ts +++ b/dapp/src/theme/utils/zIndices.ts @@ -1,4 +1,5 @@ export const zIndices = { sidebar: 1450, drawer: 1470, + toast: 1410, } From de5628212fce2a147c5c0d7cccbac39cc24549bc Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Mon, 18 Mar 2024 10:25:02 +0100 Subject: [PATCH 026/110] Update `estimateStakingFees` in staking module Sum up all network fees and add total field - we decided to add a total field because the SDK should be responsible for summing up all fees. If we add a new fee in the future the consumers will have to update their code as well which is not a developer-friendly approach. --- sdk/src/modules/staking/index.ts | 41 +++++++++++++++++--------- sdk/test/modules/staking.test.ts | 49 +++++++++++++------------------- 2 files changed, 47 insertions(+), 43 deletions(-) diff --git a/sdk/src/modules/staking/index.ts b/sdk/src/modules/staking/index.ts index 23f9ae3ee..44c39dda2 100644 --- a/sdk/src/modules/staking/index.ts +++ b/sdk/src/modules/staking/index.ts @@ -1,9 +1,22 @@ import { ChainIdentifier, TBTC } from "@keep-network/tbtc-v2.ts" -import { AcreContracts, DepositorProxy, StakingFees } from "../../lib/contracts" +import { + AcreContracts, + DepositorProxy, + StakingFees as StakingFeesByNetwork, +} from "../../lib/contracts" import { ChainEIP712Signer } from "../../lib/eip712-signer" import { StakeInitialization } from "./stake-initialization" import { toSatoshi } from "../../lib/utils" +/** + * Represents all total staking fees grouped by network. + */ +export type TotalStakingFees = { + tbtc: bigint + acre: bigint + total: bigint +} + /** * Module exposing features related to the staking. */ @@ -84,24 +97,26 @@ class StakingModule { * Estimates the staking fees based on the provided amount. * @param amountToStake Amount to stake in satoshi. * @returns Staking fees grouped by tBTC and Acre networks in 1e8 satoshi - * precision. + * precision and total staking fees value. */ - async estimateStakingFees(amount: bigint): Promise { - const { acre, tbtc } = + async estimateStakingFees(amount: bigint): Promise { + const { acre: acreFees, tbtc: tbtcFees } = await this.#contracts.bitcoinDepositor.estimateStakingFees(amount) - const feesToSatoshi = ( + const sumFeesByNetwork = < + T extends StakingFeesByNetwork["tbtc"] | StakingFeesByNetwork["acre"], + >( fees: T, - ) => - Object.entries(fees).reduce( - (reducer, [key, value]) => - Object.assign(reducer, { [key]: toSatoshi(value) }), - {} as T, - ) + ) => Object.values(fees).reduce((reducer, fee) => reducer + fee, 0n) + + const tbtc = toSatoshi(sumFeesByNetwork(tbtcFees)) + + const acre = toSatoshi(sumFeesByNetwork(acreFees)) return { - tbtc: feesToSatoshi(tbtc), - acre: feesToSatoshi(acre), + tbtc, + acre, + total: tbtc + acre, } } } diff --git a/sdk/test/modules/staking.test.ts b/sdk/test/modules/staking.test.ts index ee76c9146..b95350ca8 100644 --- a/sdk/test/modules/staking.test.ts +++ b/sdk/test/modules/staking.test.ts @@ -9,6 +9,7 @@ import { DepositReceipt, EthereumAddress, StakingFees, + TotalStakingFees, } from "../../src" import * as satoshiConverter from "../../src/lib/utils/satoshi-converter" import { MockAcreContracts } from "../utils/mock-acre-contracts" @@ -26,7 +27,7 @@ const stakingModuleData: { estimateStakingFees: { amount: bigint mockedStakingFees: StakingFees - expectedStakingFeesInSatoshi: StakingFees + expectedStakingFeesInSatoshi: TotalStakingFees } } = { initializeStake: { @@ -56,18 +57,9 @@ const stakingModuleData: { }, }, expectedStakingFeesInSatoshi: { - tbtc: { - // 0.00005 BTC in 1e8 satoshi precision. - treasuryFee: 5000n, - // 0.001 BTC in 1e8 satoshi precision. - depositTxMaxFee: 100000n, - // 0.0001999 BTC in 1e8 satoshi precision. - optimisticMintingFee: 19990n, - }, - acre: { - // 0.0001 BTC in 1e8 satoshi precision. - depositorFee: 10000n, - }, + tbtc: 124990n, + acre: 10000n, + total: 134990n, }, }, } @@ -443,13 +435,14 @@ describe("Staking", () => { }, } = stakingModuleData - let result: StakingFees + let result: TotalStakingFees const spyOnToSatoshi = jest.spyOn(satoshiConverter, "toSatoshi") beforeAll(async () => { contracts.bitcoinDepositor.estimateStakingFees = jest .fn() .mockResolvedValue(mockedStakingFees) + result = await staking.estimateStakingFees(amount) }) @@ -460,25 +453,21 @@ describe("Staking", () => { }) it("should convert tBTC network fees to satoshi", () => { - expect(spyOnToSatoshi).toHaveBeenNthCalledWith( - 1, - mockedStakingFees.tbtc.treasuryFee, - ) - expect(spyOnToSatoshi).toHaveBeenNthCalledWith( - 2, - mockedStakingFees.tbtc.depositTxMaxFee, - ) - expect(spyOnToSatoshi).toHaveBeenNthCalledWith( - 3, - mockedStakingFees.tbtc.optimisticMintingFee, - ) + const { + tbtc: { depositTxMaxFee, treasuryFee, optimisticMintingFee }, + } = mockedStakingFees + const totalTbtcFees = depositTxMaxFee + treasuryFee + optimisticMintingFee + + expect(spyOnToSatoshi).toHaveBeenNthCalledWith(1, totalTbtcFees) }) it("should convert Acre network fees to satoshi", () => { - expect(spyOnToSatoshi).toHaveBeenNthCalledWith( - 4, - mockedStakingFees.acre.depositorFee, - ) + const { + acre: { depositorFee }, + } = mockedStakingFees + const totalAcreFees = depositorFee + + expect(spyOnToSatoshi).toHaveBeenNthCalledWith(2, totalAcreFees) }) it("should return the staking fees in satoshi precision", () => { From 59c15b813ef007de2c901a72db2ef46b6af43322 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Mon, 18 Mar 2024 19:11:54 +0100 Subject: [PATCH 027/110] Rename field in `AcreStakingFees` type `depositorFee` -> `bitcoinDepositorFee` --- sdk/src/lib/contracts/bitcoin-depositor.ts | 6 +++--- sdk/src/lib/ethereum/bitcoin-depositor.ts | 2 +- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 2 +- sdk/test/modules/staking.test.ts | 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/sdk/src/lib/contracts/bitcoin-depositor.ts b/sdk/src/lib/contracts/bitcoin-depositor.ts index 3e1120dd5..4966eacf5 100644 --- a/sdk/src/lib/contracts/bitcoin-depositor.ts +++ b/sdk/src/lib/contracts/bitcoin-depositor.ts @@ -37,10 +37,10 @@ type TBTCMintingFees = { */ type AcreStakingFees = { /** - * The Acre network depositor fee taken from each deposit and transferred to - * the treasury upon stake request finalization. + * The Acre network depositor fee taken from each Bitcoin deposit and + * transferred to the treasury upon stake request finalization. */ - depositorFee: bigint + bitcoinDepositorFee: bigint } export type StakingFees = { diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index ea327a023..385974700 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -185,7 +185,7 @@ class EthereumBitcoinDepositor depositTxMaxFee: depositTxMaxFee * this.#satoshiMultiplier, }, acre: { - depositorFee, + bitcoinDepositorFee: depositorFee, }, } } diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index 7ef9a6fe5..7157c0961 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -297,7 +297,7 @@ describe("BitcoinDepositor", () => { // and transferred to the treasury upon stake request finalization. // `depositorFee = depositedAmount / depositorFeeDivisor` // 0.0001 tBTC in 1e18 precision. - depositorFee: 100000000000000n, + bitcoinDepositorFee: 100000000000000n, }, } diff --git a/sdk/test/modules/staking.test.ts b/sdk/test/modules/staking.test.ts index b95350ca8..1824a6a64 100644 --- a/sdk/test/modules/staking.test.ts +++ b/sdk/test/modules/staking.test.ts @@ -53,7 +53,7 @@ const stakingModuleData: { }, acre: { // 0.0001 tBTC in 1e18 precision. - depositorFee: 100000000000000n, + bitcoinDepositorFee: 100000000000000n, }, }, expectedStakingFeesInSatoshi: { @@ -463,9 +463,9 @@ describe("Staking", () => { it("should convert Acre network fees to satoshi", () => { const { - acre: { depositorFee }, + acre: { bitcoinDepositorFee }, } = mockedStakingFees - const totalAcreFees = depositorFee + const totalAcreFees = bitcoinDepositorFee expect(spyOnToSatoshi).toHaveBeenNthCalledWith(2, totalAcreFees) }) From c706f8890e79b7b73ef691ed00a0d6c385ccee61 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Mon, 18 Mar 2024 19:25:20 +0100 Subject: [PATCH 028/110] Combine all tBTC Bridge params in one obj and fn --- sdk/src/lib/ethereum/bitcoin-depositor.ts | 51 +++++++---------------- 1 file changed, 14 insertions(+), 37 deletions(-) diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index 385974700..d99731cda 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -33,6 +33,10 @@ type TbtcDepositParameters = { depositTxMaxFee: bigint } +type TbtcBridgeMintingParameters = TbtcDepositParameters & { + optimisticMintingFeeDivisor: bigint +} + /** * Ethereum implementation of the BitcoinDepositor. */ @@ -48,9 +52,7 @@ class EthereumBitcoinDepositor */ readonly #satoshiMultiplier = 10n ** 10n - #tbtcBridgeDepositsParameters: TbtcDepositParameters | undefined - - #tbtcOptimisticMintingFeeDivisor: bigint | undefined + #tbtcBridgeMintingParameters: TbtcBridgeMintingParameters | undefined constructor(config: EthersContractConfig, network: EthereumNetwork) { let artifact: EthersContractDeployment @@ -153,7 +155,7 @@ class EthereumBitcoinDepositor depositTreasuryFeeDivisor, depositTxMaxFee, optimisticMintingFeeDivisor, - } = await this.#getTbtcMintingFeesParameters() + } = await this.#getTbtcBridgeMintingParameters() const treasuryFee = depositTreasuryFeeDivisor > 0 @@ -190,55 +192,30 @@ class EthereumBitcoinDepositor } } - async #getTbtcMintingFeesParameters(): Promise< - TbtcDepositParameters & { optimisticMintingFeeDivisor: bigint } - > { - const depositParameters = await this.#getTbtcDepositParameters() - const optimisticMintingFeeDivisor = - await this.#getTbtcOptimisticMintingFeeDivisor() - - return { - ...depositParameters, - optimisticMintingFeeDivisor, - } - } - - async #getTbtcDepositParameters(): Promise { - if (this.#tbtcBridgeDepositsParameters) { - return this.#tbtcBridgeDepositsParameters + async #getTbtcBridgeMintingParameters(): Promise { + if (this.#tbtcBridgeMintingParameters) { + return this.#tbtcBridgeMintingParameters } const bridgeAddress = await this.instance.bridge() - const bridge = new Contract(bridgeAddress, [ "function depositsParameters()", ]) - const depositsParameters = (await bridge.depositsParameters()) as TbtcDepositParameters - this.#tbtcBridgeDepositsParameters = depositsParameters - - return depositsParameters - } - - async #getTbtcOptimisticMintingFeeDivisor(): Promise { - if (this.#tbtcOptimisticMintingFeeDivisor) { - return this.#tbtcOptimisticMintingFeeDivisor - } - const vaultAddress = await this.getTbtcVaultChainIdentifier() - const vault = new Contract(`0x${vaultAddress.identifierHex}`, [ "function optimisticMintingFeeDivisor()", ]) - const optimisticMintingFeeDivisor = (await vault.optimisticMintingFeeDivisor()) as bigint - this.#tbtcOptimisticMintingFeeDivisor = optimisticMintingFeeDivisor - - return optimisticMintingFeeDivisor + this.#tbtcBridgeMintingParameters = { + ...depositsParameters, + optimisticMintingFeeDivisor, + } + return this.#tbtcBridgeMintingParameters } } From a743b88e85cf8b5a2ece21495de406043b8928a2 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Mon, 18 Mar 2024 19:41:24 +0100 Subject: [PATCH 029/110] Add `fromSatoshi` utils function Add `fromSatoshi` fn that converts an amount from `1e8` to `1e18` token precision. Also here we remove optional `fromPrecision` param in `toSatoshi` fn - we assume we always convert from `1e18` to `1e8` and in `fromSatoshi` we always convert from `1e8` to `1e18`. --- sdk/src/lib/ethereum/bitcoin-depositor.ts | 16 +++++----------- sdk/src/lib/utils/satoshi-converter.ts | 14 +++++++++----- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index d99731cda..adb6221db 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -23,7 +23,7 @@ import { EthersContractDeployment, EthersContractWrapper, } from "./contract" -import { Hex } from "../utils" +import { Hex, fromSatoshi } from "../utils" import { EthereumNetwork } from "./network" import SepoliaBitcoinDepositor from "./artifacts/sepolia/AcreBitcoinDepositor.json" @@ -47,11 +47,6 @@ class EthereumBitcoinDepositor extends EthersContractWrapper implements BitcoinDepositor { - /** - * Multiplier to convert satoshi to tBTC token units. - */ - readonly #satoshiMultiplier = 10n ** 10n - #tbtcBridgeMintingParameters: TbtcBridgeMintingParameters | undefined constructor(config: EthersContractConfig, network: EthereumNetwork) { @@ -164,8 +159,7 @@ class EthereumBitcoinDepositor // Both deposit amount and treasury fee are in the 1e8 satoshi precision. // We need to convert them to the 1e18 TBTC precision. - const amountSubTreasury = - (amountToStake - treasuryFee) * this.#satoshiMultiplier + const amountSubTreasury = fromSatoshi(amountToStake - treasuryFee) const optimisticMintingFee = optimisticMintingFeeDivisor > 0 @@ -177,14 +171,14 @@ class EthereumBitcoinDepositor // transaction amount, before the tBTC protocol network fees were taken. const depositorFee = depositorFeeDivisor > 0n - ? (amountToStake * this.#satoshiMultiplier) / depositorFeeDivisor + ? fromSatoshi(amountToStake) / depositorFeeDivisor : 0n return { tbtc: { - treasuryFee: treasuryFee * this.#satoshiMultiplier, + treasuryFee: fromSatoshi(treasuryFee), optimisticMintingFee, - depositTxMaxFee: depositTxMaxFee * this.#satoshiMultiplier, + depositTxMaxFee: fromSatoshi(depositTxMaxFee), }, acre: { bitcoinDepositorFee: depositorFee, diff --git a/sdk/src/lib/utils/satoshi-converter.ts b/sdk/src/lib/utils/satoshi-converter.ts index 8c43de3e2..8178a15d4 100644 --- a/sdk/src/lib/utils/satoshi-converter.ts +++ b/sdk/src/lib/utils/satoshi-converter.ts @@ -1,11 +1,15 @@ -const BTC_DECIMALS = 8n - -// eslint-disable-next-line import/prefer-default-export -export function toSatoshi(amount: bigint, fromPrecision: bigint = 18n) { - const SATOSHI_MULTIPLIER = 10n ** (fromPrecision - BTC_DECIMALS) +/** + * Multiplier to convert satoshi to 1e18 precision. + */ +const SATOSHI_MULTIPLIER = 10n ** 10n +export function toSatoshi(amount: bigint) { const remainder = amount % SATOSHI_MULTIPLIER const satoshis = (amount - remainder) / SATOSHI_MULTIPLIER return satoshis } + +export function fromSatoshi(amount: bigint) { + return amount * SATOSHI_MULTIPLIER +} From fb089a590589c18b14cdf520f8c3ac80eb352d46 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Mon, 18 Mar 2024 19:46:00 +0100 Subject: [PATCH 030/110] Leave `TODO` We should consider exposing the tBTC Bridge minting parameters from tTBC SDK. --- sdk/src/lib/ethereum/bitcoin-depositor.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index adb6221db..781d1fe91 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -186,6 +186,7 @@ class EthereumBitcoinDepositor } } + // TODO: Consider exposing it from tBTC SDK. async #getTbtcBridgeMintingParameters(): Promise { if (this.#tbtcBridgeMintingParameters) { return this.#tbtcBridgeMintingParameters From a1273222598c0af269ebd6fd6ea58f79216ae49c Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Mon, 18 Mar 2024 19:54:41 +0100 Subject: [PATCH 031/110] Cache `depositorFeeDivisor` This parameter will not change frequently, so we can cache this value per instance. --- sdk/src/lib/ethereum/bitcoin-depositor.ts | 33 ++++++++++++++++---- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 7 +++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index 781d1fe91..ecb403ce4 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -37,6 +37,11 @@ type TbtcBridgeMintingParameters = TbtcDepositParameters & { optimisticMintingFeeDivisor: bigint } +type BitcoinDepositorCache = { + tbtcBridgeMintingParameters: TbtcBridgeMintingParameters | undefined + depositorFeeDivisor: bigint | undefined +} + /** * Ethereum implementation of the BitcoinDepositor. */ @@ -47,7 +52,7 @@ class EthereumBitcoinDepositor extends EthersContractWrapper implements BitcoinDepositor { - #tbtcBridgeMintingParameters: TbtcBridgeMintingParameters | undefined + #cache: BitcoinDepositorCache constructor(config: EthersContractConfig, network: EthereumNetwork) { let artifact: EthersContractDeployment @@ -62,6 +67,10 @@ class EthereumBitcoinDepositor } super(config, artifact) + this.#cache = { + tbtcBridgeMintingParameters: undefined, + depositorFeeDivisor: undefined, + } } /** @@ -166,7 +175,7 @@ class EthereumBitcoinDepositor ? amountSubTreasury / optimisticMintingFeeDivisor : 0n - const depositorFeeDivisor = await this.instance.depositorFeeDivisor() + const depositorFeeDivisor = await this.#depositorFeeDivisor() // Compute depositor fee. The fee is calculated based on the initial funding // transaction amount, before the tBTC protocol network fees were taken. const depositorFee = @@ -188,8 +197,8 @@ class EthereumBitcoinDepositor // TODO: Consider exposing it from tBTC SDK. async #getTbtcBridgeMintingParameters(): Promise { - if (this.#tbtcBridgeMintingParameters) { - return this.#tbtcBridgeMintingParameters + if (this.#cache.tbtcBridgeMintingParameters) { + return this.#cache.tbtcBridgeMintingParameters } const bridgeAddress = await this.instance.bridge() @@ -206,11 +215,23 @@ class EthereumBitcoinDepositor const optimisticMintingFeeDivisor = (await vault.optimisticMintingFeeDivisor()) as bigint - this.#tbtcBridgeMintingParameters = { + this.#cache.tbtcBridgeMintingParameters = { ...depositsParameters, optimisticMintingFeeDivisor, } - return this.#tbtcBridgeMintingParameters + return this.#cache.tbtcBridgeMintingParameters + } + + async #depositorFeeDivisor(): Promise { + if (this.#cache.depositorFeeDivisor) { + return this.#cache.depositorFeeDivisor + } + + const depositorFeeDivisor = await this.instance.depositorFeeDivisor() + + this.#cache.depositorFeeDivisor = depositorFeeDivisor + + return this.#cache.depositorFeeDivisor } } diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index 7157c0961..ea774c38c 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -372,6 +372,7 @@ describe("BitcoinDepositor", () => { beforeAll(async () => { mockedContractInstance.bridge.mockClear() mockedContractInstance.tbtcVault.mockClear() + mockedContractInstance.depositorFeeDivisor.mockClear() mockedBridgeContractInstance.depositsParameters.mockClear() mockedVaultContractInstance.optimisticMintingFeeDivisor.mockClear() @@ -392,6 +393,12 @@ describe("BitcoinDepositor", () => { ).toHaveBeenCalledTimes(0) }) + it("should get the bitcoin depositor fee divisor from cache", () => { + expect( + mockedContractInstance.depositorFeeDivisor, + ).toHaveBeenCalledTimes(0) + }) + it("should return correct fees", () => { expect(result2).toMatchObject(expectedResult) }) From 797603c3f22edd12d8a3292052c16685ce843d5d Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 20 Mar 2024 14:32:47 +0100 Subject: [PATCH 032/110] Fix typo for `onClick` --- dapp/src/components/shared/alerts/CardAlert.tsx | 6 +++--- dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dapp/src/components/shared/alerts/CardAlert.tsx b/dapp/src/components/shared/alerts/CardAlert.tsx index 6d242753d..1c40f8a4e 100644 --- a/dapp/src/components/shared/alerts/CardAlert.tsx +++ b/dapp/src/components/shared/alerts/CardAlert.tsx @@ -5,13 +5,13 @@ import { Alert, AlertProps } from "./Alert" export type CardAlertProps = { withLink?: boolean - onclick?: () => void + onClick?: () => void } & Omit export function CardAlert({ withLink = false, children, - onclick, + onClick, ...props }: CardAlertProps) { return ( @@ -42,7 +42,7 @@ export function CardAlert({ boxSize={4} cursor="pointer" color="brand.400" - onClick={onclick} + onClick={onClick} /> )} diff --git a/dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx b/dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx index bf3fabbfb..a8003f524 100644 --- a/dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx +++ b/dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx @@ -6,7 +6,7 @@ import { TextMd } from "../Typography" export function ReceiveSTBTCAlert({ ...restProps }: CardAlertProps) { return ( // TODO: Add the correct action after click - {}} {...restProps}> + {}} {...restProps}> You will receive stBTC liquid staking token at this Ethereum address From 6585152a66b5d76609eeb46a450ee84224e664ca Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 20 Mar 2024 14:36:27 +0100 Subject: [PATCH 033/110] Change the default status value for the `Toast` component --- dapp/src/components/shared/alerts/Toast.tsx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/dapp/src/components/shared/alerts/Toast.tsx b/dapp/src/components/shared/alerts/Toast.tsx index d97188ff3..60afe2a86 100644 --- a/dapp/src/components/shared/alerts/Toast.tsx +++ b/dapp/src/components/shared/alerts/Toast.tsx @@ -12,7 +12,7 @@ type ToastProps = { export function Toast({ title, children, onClose, ...props }: ToastProps) { return ( - + {title} {children} @@ -29,6 +29,7 @@ export const TOASTS: Record< id: TOAST_TYPES.BITCOIN_WALLET_NOT_CONNECTED_ERROR, render: ({ onClose }) => ( onClose()} @@ -50,6 +51,7 @@ export const TOASTS: Record< id: TOAST_TYPES.ETHEREUM_WALLET_NOT_CONNECTED_ERROR, render: ({ onClose }) => ( onClose()} @@ -70,7 +72,11 @@ export const TOASTS: Record< [TOAST_TYPES.SIGNING_ERROR]: () => ({ id: TOAST_TYPES.SIGNING_ERROR, render: ({ onClose }) => ( - + Please try again. ), @@ -79,6 +85,7 @@ export const TOASTS: Record< id: TOAST_TYPES.DEPOSIT_TRANSACTION_ERROR, render: ({ onClose }) => ( From ded8b11bc383f42b57418c1e77e998327b446596 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 20 Mar 2024 14:53:57 +0100 Subject: [PATCH 034/110] Rename `WALLET_TOAST` to `WALLET_ERROR_TOAST_ID` --- dapp/src/hooks/useWalletToast.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dapp/src/hooks/useWalletToast.ts b/dapp/src/hooks/useWalletToast.ts index d8d024e20..6e3901bda 100644 --- a/dapp/src/hooks/useWalletToast.ts +++ b/dapp/src/hooks/useWalletToast.ts @@ -6,7 +6,7 @@ import { TOAST_TYPES } from "#/types" import { useToast } from "./useToast" import { useWallet } from "./useWallet" -const WALLET_TOAST = { +const WALLET_ERROR_TOAST_ID = { bitcoin: TOAST_TYPES.BITCOIN_WALLET_NOT_CONNECTED_ERROR, ethereum: TOAST_TYPES.ETHEREUM_WALLET_NOT_CONNECTED_ERROR, } @@ -20,7 +20,7 @@ export function useWalletToast( } = useWallet() const { close, open } = useToast() - const toastId = WALLET_TOAST[type] + const toastId = WALLET_ERROR_TOAST_ID[type] const handleConnect = useCallback( () => logPromiseFailure(requestAccount()), From 516d3157861d5cbbf82bf7122d313af3e823d5d4 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 20 Mar 2024 15:53:39 +0100 Subject: [PATCH 035/110] Remove unnecessary disabling of the `eslint` rule --- dapp/src/hooks/useWalletToast.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/dapp/src/hooks/useWalletToast.ts b/dapp/src/hooks/useWalletToast.ts index 6e3901bda..fb088972b 100644 --- a/dapp/src/hooks/useWalletToast.ts +++ b/dapp/src/hooks/useWalletToast.ts @@ -38,7 +38,6 @@ export function useWalletToast( delay, ) - // eslint-disable-next-line consistent-return return () => clearTimeout(timeout) }, [delay, handleConnect, open, toastId, type]) From b208331c0749b7776b95ba18dd91fb903ada155b Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 20 Mar 2024 16:17:19 +0100 Subject: [PATCH 036/110] Move style for `LoadingButton` to theme --- dapp/src/components/shared/LoadingButton.tsx | 12 +----------- dapp/src/theme/Button.ts | 6 ++++++ 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/dapp/src/components/shared/LoadingButton.tsx b/dapp/src/components/shared/LoadingButton.tsx index 2066c8b0d..aa8c1715d 100644 --- a/dapp/src/components/shared/LoadingButton.tsx +++ b/dapp/src/components/shared/LoadingButton.tsx @@ -1,19 +1,9 @@ import React from "react" import { Button, ButtonProps, Spinner } from "@chakra-ui/react" -const LOADING_STYLE = { - _disabled: { background: "gold.300", opacity: 1 }, - _hover: { opacity: 1 }, -} - export function LoadingButton({ isLoading, children, ...props }: ButtonProps) { return ( - ) diff --git a/dapp/src/theme/Button.ts b/dapp/src/theme/Button.ts index f99609345..b424d1f53 100644 --- a/dapp/src/theme/Button.ts +++ b/dapp/src/theme/Button.ts @@ -27,6 +27,12 @@ export const buttonTheme: ComponentSingleStyleConfig = { _active: { bg: "brand.400", }, + _loading: { + _disabled: { + background: "gold.300", + opacity: 1, + }, + }, }, outline: ({ colorScheme }: StyleFunctionProps) => { const defaultStyles = { From 1bfe26c6043b5517790ddaa051911296c016ca5e Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Fri, 22 Mar 2024 08:02:53 +0100 Subject: [PATCH 037/110] Remove unnecessary `onClick` --- dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx b/dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx index a8003f524..d873f70b3 100644 --- a/dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx +++ b/dapp/src/components/shared/alerts/ReceiveSTBTCAlert.tsx @@ -6,7 +6,7 @@ import { TextMd } from "../Typography" export function ReceiveSTBTCAlert({ ...restProps }: CardAlertProps) { return ( // TODO: Add the correct action after click - {}} {...restProps}> + You will receive stBTC liquid staking token at this Ethereum address From f0f846a916410b121d18e5a8e74b2ab6eeef276d Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Fri, 22 Mar 2024 08:05:47 +0100 Subject: [PATCH 038/110] Improve the `onClose` function pass --- dapp/src/components/shared/alerts/Toast.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dapp/src/components/shared/alerts/Toast.tsx b/dapp/src/components/shared/alerts/Toast.tsx index 60afe2a86..24a7adfaf 100644 --- a/dapp/src/components/shared/alerts/Toast.tsx +++ b/dapp/src/components/shared/alerts/Toast.tsx @@ -32,7 +32,7 @@ export const TOASTS: Record< status="error" width="xl" title="Bitcoin wallet is not connected." - onClose={() => onClose()} + onClose={onClose} > - - - ), - }), - [TOAST_TYPES.ETHEREUM_WALLET_NOT_CONNECTED_ERROR]: (params) => ({ - id: TOAST_TYPES.ETHEREUM_WALLET_NOT_CONNECTED_ERROR, - render: ({ onClose }) => ( - - - - - - ), - }), - [TOAST_TYPES.SIGNING_ERROR]: () => ({ - id: TOAST_TYPES.SIGNING_ERROR, - render: ({ onClose }) => ( - - Please try again. - - ), - }), - [TOAST_TYPES.DEPOSIT_TRANSACTION_ERROR]: () => ({ - id: TOAST_TYPES.DEPOSIT_TRANSACTION_ERROR, - render: ({ onClose }) => ( - - Please try again. - - ), - }), -} diff --git a/dapp/src/components/shared/alerts/ToastBase.tsx b/dapp/src/components/shared/alerts/ToastBase.tsx new file mode 100644 index 000000000..98cd45e6a --- /dev/null +++ b/dapp/src/components/shared/alerts/ToastBase.tsx @@ -0,0 +1,26 @@ +import React from "react" +import { HStack } from "@chakra-ui/react" +import { Alert, AlertProps } from "./Alert" +import { TextSm } from "../Typography" + +type ToastBaseProps = { + title: string +} & Omit & { + onClose: () => void + } + +export function ToastBase({ + title, + children, + onClose, + ...props +}: ToastBaseProps) { + return ( + + + {title} + {children} + + + ) +} diff --git a/dapp/src/components/shared/alerts/index.tsx b/dapp/src/components/shared/alerts/index.ts similarity index 75% rename from dapp/src/components/shared/alerts/index.tsx rename to dapp/src/components/shared/alerts/index.ts index ae4273f89..c9cbfceff 100644 --- a/dapp/src/components/shared/alerts/index.tsx +++ b/dapp/src/components/shared/alerts/index.ts @@ -1,4 +1,4 @@ export * from "./Alert" export * from "./CardAlert" export * from "./ReceiveSTBTCAlert" -export * from "./Toast" +export * from "./ToastBase" diff --git a/dapp/src/components/shared/toasts/DepositTransactionErrorToast.tsx b/dapp/src/components/shared/toasts/DepositTransactionErrorToast.tsx new file mode 100644 index 000000000..59c9f2332 --- /dev/null +++ b/dapp/src/components/shared/toasts/DepositTransactionErrorToast.tsx @@ -0,0 +1,19 @@ +import React from "react" +import { TextSm } from "../Typography" +import { ToastBase } from "../alerts" + +export function DepositTransactionErrorToast({ + onClose, +}: { + onClose: () => void +}) { + return ( + + Please try again. + + ) +} diff --git a/dapp/src/components/shared/toasts/MessageSigningErrorToast.tsx b/dapp/src/components/shared/toasts/MessageSigningErrorToast.tsx new file mode 100644 index 000000000..c9bebd0ef --- /dev/null +++ b/dapp/src/components/shared/toasts/MessageSigningErrorToast.tsx @@ -0,0 +1,15 @@ +import React from "react" +import { TextSm } from "../Typography" +import { ToastBase } from "../alerts" + +export function MessageSigningErrorToast({ onClose }: { onClose: () => void }) { + return ( + + Please try again. + + ) +} diff --git a/dapp/src/components/shared/toasts/WalletErrorToast.tsx b/dapp/src/components/shared/toasts/WalletErrorToast.tsx new file mode 100644 index 000000000..1d30869f8 --- /dev/null +++ b/dapp/src/components/shared/toasts/WalletErrorToast.tsx @@ -0,0 +1,23 @@ +import React from "react" +import { Flex, Button } from "@chakra-ui/react" +import { ToastBase } from "../alerts" + +export function WalletErrorToast({ + title, + onClick, + onClose, +}: { + title: string + onClick?: () => void + onClose: () => void +}) { + return ( + + + + + + ) +} diff --git a/dapp/src/components/shared/toasts/index.ts b/dapp/src/components/shared/toasts/index.ts new file mode 100644 index 000000000..9d37898ac --- /dev/null +++ b/dapp/src/components/shared/toasts/index.ts @@ -0,0 +1,4 @@ +export * from "./MessageSigningErrorToast" +export * from "./DepositTransactionErrorToast" +export * from "./WalletErrorToast" +export * from "./toasts" diff --git a/dapp/src/components/shared/toasts/toasts.tsx b/dapp/src/components/shared/toasts/toasts.tsx new file mode 100644 index 000000000..4c3a1160d --- /dev/null +++ b/dapp/src/components/shared/toasts/toasts.tsx @@ -0,0 +1,47 @@ +import React from "react" +import { TOAST_TYPES, ToastType } from "#/types" +import { UseToastOptions } from "@chakra-ui/react" +import { WalletErrorToast } from "./WalletErrorToast" +import { MessageSigningErrorToast } from "./MessageSigningErrorToast" +import { DepositTransactionErrorToast } from "./DepositTransactionErrorToast" + +const { + BITCOIN_WALLET_NOT_CONNECTED_ERROR, + ETHEREUM_WALLET_NOT_CONNECTED_ERROR, + SIGNING_ERROR, + DEPOSIT_TRANSACTION_ERROR, +} = TOAST_TYPES + +export const TOASTS: Record< + ToastType, + (params?: { onClick: () => void }) => UseToastOptions +> = { + [BITCOIN_WALLET_NOT_CONNECTED_ERROR]: (params) => ({ + id: BITCOIN_WALLET_NOT_CONNECTED_ERROR, + render: ({ onClose }) => ( + + ), + }), + [ETHEREUM_WALLET_NOT_CONNECTED_ERROR]: (params) => ({ + id: ETHEREUM_WALLET_NOT_CONNECTED_ERROR, + render: ({ onClose }) => ( + + ), + }), + [SIGNING_ERROR]: () => ({ + id: SIGNING_ERROR, + render: ({ onClose }) => , + }), + [DEPOSIT_TRANSACTION_ERROR]: () => ({ + id: DEPOSIT_TRANSACTION_ERROR, + render: ({ onClose }) => , + }), +} diff --git a/dapp/src/hooks/useWalletToast.ts b/dapp/src/hooks/useWalletToast.ts index fb088972b..cc146e4cd 100644 --- a/dapp/src/hooks/useWalletToast.ts +++ b/dapp/src/hooks/useWalletToast.ts @@ -1,8 +1,8 @@ import { useCallback, useEffect } from "react" import { ONE_SEC_IN_MILLISECONDS } from "#/constants" import { logPromiseFailure } from "#/utils" -import { TOASTS } from "#/components/shared/alerts" import { TOAST_TYPES } from "#/types" +import { TOASTS } from "#/components/shared/toasts" import { useToast } from "./useToast" import { useWallet } from "./useWallet" From 7853840033d483424de1f095addd40802ca5fae2 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 2 Apr 2024 08:47:31 +0200 Subject: [PATCH 041/110] Rename from `overriddenToastFunction` to `overriddenToast` --- dapp/src/hooks/useToast.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/dapp/src/hooks/useToast.ts b/dapp/src/hooks/useToast.ts index 9b253dc29..60dbee49d 100644 --- a/dapp/src/hooks/useToast.ts +++ b/dapp/src/hooks/useToast.ts @@ -4,7 +4,7 @@ import { useCallback, useMemo } from "react" export function useToast() { const toast = useChakraToast() - const overriddenToastFunction = useCallback( + const overriddenToast = useCallback( (options: UseToastOptions) => toast({ position: "top", @@ -19,22 +19,22 @@ export function useToast() { const open = useCallback( ({ id, ...options }: UseToastOptions) => { if (!id) { - overriddenToastFunction(options) + overriddenToast(options) } else if (!toast.isActive(id)) { - overriddenToastFunction({ + overriddenToast({ id, ...options, }) } }, - [overriddenToastFunction, toast], + [overriddenToast, toast], ) return useMemo( () => ({ - ...Object.assign(overriddenToastFunction, toast), + ...Object.assign(overriddenToast, toast), open, }), - [overriddenToastFunction, toast, open], + [overriddenToast, toast, open], ) } From 7632242e02a45636a80d10d7f38cd31183634740 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 2 Apr 2024 09:19:58 +0200 Subject: [PATCH 042/110] Create a `useTimeout` hook --- dapp/src/hooks/index.ts | 1 + dapp/src/hooks/useTimeout.ts | 25 +++++++++++++++++++++++++ dapp/src/hooks/useWalletToast.ts | 25 ++++++++++++------------- 3 files changed, 38 insertions(+), 13 deletions(-) create mode 100644 dapp/src/hooks/useTimeout.ts diff --git a/dapp/src/hooks/index.ts b/dapp/src/hooks/index.ts index dd0dba80c..2a1408832 100644 --- a/dapp/src/hooks/index.ts +++ b/dapp/src/hooks/index.ts @@ -20,3 +20,4 @@ export * from "./useFetchBTCPriceUSD" export * from "./useToast" export * from "./useWallet" export * from "./useWalletToast" +export * from "./useTimeout" diff --git a/dapp/src/hooks/useTimeout.ts b/dapp/src/hooks/useTimeout.ts new file mode 100644 index 000000000..ba037809e --- /dev/null +++ b/dapp/src/hooks/useTimeout.ts @@ -0,0 +1,25 @@ +import { useEffect, useLayoutEffect, useRef } from "react" + +// Source: https://usehooks-ts.com/react-hook/use-timeout +export function useTimeout(callback: () => void, delay: number | null) { + const savedCallback = useRef(callback) + + // Remember the latest callback if it changes. + useLayoutEffect(() => { + savedCallback.current = callback + }, [callback]) + + // Set up the timeout. + useEffect(() => { + // Don't schedule if no delay is specified. + // Note: 0 is a valid value for delay. + if (!delay && delay !== 0) { + return + } + + const id = setTimeout(() => savedCallback.current(), delay) + + // eslint-disable-next-line consistent-return + return () => clearTimeout(id) + }, [delay]) +} diff --git a/dapp/src/hooks/useWalletToast.ts b/dapp/src/hooks/useWalletToast.ts index cc146e4cd..32dfa00e2 100644 --- a/dapp/src/hooks/useWalletToast.ts +++ b/dapp/src/hooks/useWalletToast.ts @@ -5,6 +5,7 @@ import { TOAST_TYPES } from "#/types" import { TOASTS } from "#/components/shared/toasts" import { useToast } from "./useToast" import { useWallet } from "./useWallet" +import { useTimeout } from "./useTimeout" const WALLET_ERROR_TOAST_ID = { bitcoin: TOAST_TYPES.BITCOIN_WALLET_NOT_CONNECTED_ERROR, @@ -27,19 +28,17 @@ export function useWalletToast( [requestAccount], ) - useEffect(() => { - const timeout = setTimeout( - () => - open( - TOASTS[toastId]({ - onClick: handleConnect, - }), - ), - delay, - ) - - return () => clearTimeout(timeout) - }, [delay, handleConnect, open, toastId, type]) + const handleOpen = useCallback( + () => + open( + TOASTS[toastId]({ + onClick: handleConnect, + }), + ), + [handleConnect, open, toastId], + ) + + useTimeout(handleOpen, delay) useEffect(() => { if (!account) return From 45842488f0aba8ae312f9eea3591c36d33a69e4f Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 2 Apr 2024 09:21:43 +0200 Subject: [PATCH 043/110] Rename from `toastManagerStyle` to `toastManagerTopStyle` --- dapp/src/theme/utils/styles.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dapp/src/theme/utils/styles.ts b/dapp/src/theme/utils/styles.ts index 71be2dc70..a1a891663 100644 --- a/dapp/src/theme/utils/styles.ts +++ b/dapp/src/theme/utils/styles.ts @@ -9,7 +9,7 @@ const bodyStyle = defineStyle((props: StyleFunctionProps) => ({ color: mode("grey.700", "grey.700")(props), })) -const toastManagerStyle = defineStyle({ +const toastManagerTopStyle = defineStyle({ marginTop: `${semanticTokens.space.toast_container_shift} !important`, // To set the correct z-index value for the toast component, // we need to override it in the global styles @@ -19,7 +19,7 @@ const toastManagerStyle = defineStyle({ }) const globalStyle = (props: StyleFunctionProps) => ({ - "#chakra-toast-manager-top": toastManagerStyle, + "#chakra-toast-manager-top": toastManagerTopStyle, body: bodyStyle(props), }) From e99d2e579388b86302ac1766d2df16a751cd5dae Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 2 Apr 2024 09:24:01 +0200 Subject: [PATCH 044/110] Remove unnecessary padding for tooltip --- dapp/src/components/shared/ActivityBar/ActivityCard.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dapp/src/components/shared/ActivityBar/ActivityCard.tsx b/dapp/src/components/shared/ActivityBar/ActivityCard.tsx index 8682c0964..dcf0ca46e 100644 --- a/dapp/src/components/shared/ActivityBar/ActivityCard.tsx +++ b/dapp/src/components/shared/ActivityBar/ActivityCard.tsx @@ -50,7 +50,7 @@ function ActivityCard({ activity, onRemove }: ActivityCardType) { symbolFontWeight="medium" /> {isCompleted ? ( - + ) : ( From 33a042117c7f7ccd89e2f56bab3772da6fabf4d8 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 2 Apr 2024 10:37:09 +0200 Subject: [PATCH 045/110] Removal of the global object `TOASTS` The previous approach created a bit of a mess. To call a specific toast we needed to provide an id. Currently, the solution allows a specific toast to be called directly in the area of use. --- .../Table/utils/columns.tsx | 10 ++-- .../ActiveStakingStep/DepositBTCModal.tsx | 8 ++-- .../ActiveStakingStep/SignMessageModal.tsx | 11 +++-- .../shared/ActivityBar/ActivityCard.tsx | 4 +- dapp/src/components/shared/toasts/index.ts | 1 - dapp/src/components/shared/toasts/toasts.tsx | 47 ------------------- dapp/src/hooks/useWalletToast.ts | 25 +++++----- .../pages/ActivityPage/ActivityDetails.tsx | 4 +- dapp/src/types/index.ts | 1 - dapp/src/types/toast.ts | 8 ---- dapp/src/utils/text.ts | 2 +- 11 files changed, 37 insertions(+), 84 deletions(-) delete mode 100644 dapp/src/components/shared/toasts/toasts.tsx delete mode 100644 dapp/src/types/toast.ts diff --git a/dapp/src/components/TransactionHistory/Table/utils/columns.tsx b/dapp/src/components/TransactionHistory/Table/utils/columns.tsx index 7523e56f8..d656a50ea 100644 --- a/dapp/src/components/TransactionHistory/Table/utils/columns.tsx +++ b/dapp/src/components/TransactionHistory/Table/utils/columns.tsx @@ -1,7 +1,7 @@ import React from "react" import { ColumnDef, createColumnHelper } from "@tanstack/react-table" import { StakeHistory } from "#/types" -import { capitalize, truncateAddress } from "#/utils" +import { capitalizeFirstLetter, truncateAddress } from "#/utils" import CustomCell from "../Cell/Custom" import Cell from "../Cell" import SimpleText from "../Cell/components/SimpleText" @@ -32,10 +32,14 @@ export const COLUMNS: ColumnDef[] = [ cell: ({ row: { original } }) => ( {capitalize(original.callTx.action)} + + {capitalizeFirstLetter(original.callTx.action)} + } secondField={ - {capitalize(original.receiptTx.action)} + + {capitalizeFirstLetter(original.receiptTx.action)} + } /> ), diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index 76f82cd2f..649da9e3a 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -11,12 +11,12 @@ import { } from "#/hooks" import { TextMd } from "#/components/shared/Typography" import { logPromiseFailure } from "#/utils" -import { PROCESS_STATUSES, TOAST_TYPES } from "#/types" +import { PROCESS_STATUSES } from "#/types" import { CardAlert } from "#/components/shared/alerts" -import { TOASTS } from "#/components/shared/toasts" +import { DepositTransactionErrorToast } from "#/components/shared/toasts" import StakingStepsModalContent from "./StakingStepsModalContent" -const TOAST_ID = TOAST_TYPES.DEPOSIT_TRANSACTION_ERROR +const TOAST_ID = "deposit-transaction-error" export default function DepositBTCModal() { const { ethAccount } = useWalletContext() @@ -53,7 +53,7 @@ export default function DepositBTCModal() { }, [closeToast, setStatus, handleStake]) const showError = useCallback(() => { - openToast(TOASTS[TOAST_ID]()) + openToast({ id: TOAST_ID, render: DepositTransactionErrorToast }) setButtonText("Try again") }, [openToast]) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx index ea2c09a58..7389990db 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx @@ -6,12 +6,12 @@ import { useToast, } from "#/hooks" import { logPromiseFailure } from "#/utils" -import { PROCESS_STATUSES, TOAST_TYPES } from "#/types" +import { PROCESS_STATUSES } from "#/types" import { ReceiveSTBTCAlert } from "#/components/shared/alerts" -import { TOASTS } from "#/components/shared/toasts" +import { MessageSigningErrorToast } from "#/components/shared/toasts" import StakingStepsModalContent from "./StakingStepsModalContent" -const TOAST_ID = TOAST_TYPES.SIGNING_ERROR +const TOAST_ID = "signing-error" export default function SignMessageModal() { const { goNext, setStatus } = useModalFlowContext() @@ -29,7 +29,10 @@ export default function SignMessageModal() { }, [closeToast, goNext]) const onSignMessageError = useCallback(() => { - openToast(TOASTS[TOAST_ID]()) + openToast({ + id: TOAST_ID, + render: MessageSigningErrorToast, + }) setButtonText("Try again") }, [openToast]) diff --git a/dapp/src/components/shared/ActivityBar/ActivityCard.tsx b/dapp/src/components/shared/ActivityBar/ActivityCard.tsx index dcf0ca46e..55ae9c4d2 100644 --- a/dapp/src/components/shared/ActivityBar/ActivityCard.tsx +++ b/dapp/src/components/shared/ActivityBar/ActivityCard.tsx @@ -11,7 +11,7 @@ import { } from "@chakra-ui/react" import { useLocation } from "react-router-dom" import { ActivityInfo, LocationState } from "#/types" -import { capitalize } from "#/utils" +import { capitalizeFirstLetter } from "#/utils" import { ChevronRightIcon } from "#/assets/icons" import { CurrencyBalance } from "#/components/shared/CurrencyBalance" import StatusInfo from "#/components/shared/StatusInfo" @@ -65,7 +65,7 @@ function ActivityCard({ activity, onRemove }: ActivityCardType) { - {capitalize(activity.action)} + {capitalizeFirstLetter(activity.action)} diff --git a/dapp/src/components/shared/toasts/index.ts b/dapp/src/components/shared/toasts/index.ts index 9d37898ac..9b997f38e 100644 --- a/dapp/src/components/shared/toasts/index.ts +++ b/dapp/src/components/shared/toasts/index.ts @@ -1,4 +1,3 @@ export * from "./MessageSigningErrorToast" export * from "./DepositTransactionErrorToast" export * from "./WalletErrorToast" -export * from "./toasts" diff --git a/dapp/src/components/shared/toasts/toasts.tsx b/dapp/src/components/shared/toasts/toasts.tsx deleted file mode 100644 index 4c3a1160d..000000000 --- a/dapp/src/components/shared/toasts/toasts.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import React from "react" -import { TOAST_TYPES, ToastType } from "#/types" -import { UseToastOptions } from "@chakra-ui/react" -import { WalletErrorToast } from "./WalletErrorToast" -import { MessageSigningErrorToast } from "./MessageSigningErrorToast" -import { DepositTransactionErrorToast } from "./DepositTransactionErrorToast" - -const { - BITCOIN_WALLET_NOT_CONNECTED_ERROR, - ETHEREUM_WALLET_NOT_CONNECTED_ERROR, - SIGNING_ERROR, - DEPOSIT_TRANSACTION_ERROR, -} = TOAST_TYPES - -export const TOASTS: Record< - ToastType, - (params?: { onClick: () => void }) => UseToastOptions -> = { - [BITCOIN_WALLET_NOT_CONNECTED_ERROR]: (params) => ({ - id: BITCOIN_WALLET_NOT_CONNECTED_ERROR, - render: ({ onClose }) => ( - - ), - }), - [ETHEREUM_WALLET_NOT_CONNECTED_ERROR]: (params) => ({ - id: ETHEREUM_WALLET_NOT_CONNECTED_ERROR, - render: ({ onClose }) => ( - - ), - }), - [SIGNING_ERROR]: () => ({ - id: SIGNING_ERROR, - render: ({ onClose }) => , - }), - [DEPOSIT_TRANSACTION_ERROR]: () => ({ - id: DEPOSIT_TRANSACTION_ERROR, - render: ({ onClose }) => , - }), -} diff --git a/dapp/src/hooks/useWalletToast.ts b/dapp/src/hooks/useWalletToast.ts index 32dfa00e2..9e01c2b37 100644 --- a/dapp/src/hooks/useWalletToast.ts +++ b/dapp/src/hooks/useWalletToast.ts @@ -1,15 +1,14 @@ import { useCallback, useEffect } from "react" import { ONE_SEC_IN_MILLISECONDS } from "#/constants" -import { logPromiseFailure } from "#/utils" -import { TOAST_TYPES } from "#/types" -import { TOASTS } from "#/components/shared/toasts" +import { capitalizeFirstLetter, logPromiseFailure } from "#/utils" +import { WalletErrorToast } from "#/components/shared/toasts" import { useToast } from "./useToast" import { useWallet } from "./useWallet" import { useTimeout } from "./useTimeout" const WALLET_ERROR_TOAST_ID = { - bitcoin: TOAST_TYPES.BITCOIN_WALLET_NOT_CONNECTED_ERROR, - ethereum: TOAST_TYPES.ETHEREUM_WALLET_NOT_CONNECTED_ERROR, + bitcoin: "bitcoin-wallet-error", + ethereum: "ethereum-wallet-error", } export function useWalletToast( @@ -30,12 +29,16 @@ export function useWalletToast( const handleOpen = useCallback( () => - open( - TOASTS[toastId]({ - onClick: handleConnect, - }), - ), - [handleConnect, open, toastId], + open({ + id: toastId, + render: ({ onClose }) => + WalletErrorToast({ + title: capitalizeFirstLetter(`${type} wallet is not connected`), + onClose, + onClick: handleConnect, + }), + }), + [handleConnect, open, toastId, type], ) useTimeout(handleOpen, delay) diff --git a/dapp/src/pages/ActivityPage/ActivityDetails.tsx b/dapp/src/pages/ActivityPage/ActivityDetails.tsx index 05f82fd82..f6feb5f76 100644 --- a/dapp/src/pages/ActivityPage/ActivityDetails.tsx +++ b/dapp/src/pages/ActivityPage/ActivityDetails.tsx @@ -10,7 +10,7 @@ import { Flex, Text, } from "@chakra-ui/react" -import { capitalize } from "#/utils" +import { capitalizeFirstLetter } from "#/utils" import ActivityProgress from "#/assets/images/activity-progress.png" import { LocationState } from "#/types" import StatusInfo from "#/components/shared/StatusInfo" @@ -47,7 +47,7 @@ function ActivityDetails() { - {capitalize(activity.action)} + {capitalizeFirstLetter(activity.action)} +export const capitalizeFirstLetter = (text: string): string => text[0].toUpperCase() + text.slice(1) From e5f8eca33287c3c35a18dddbf5be3d8215a66dbf Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 2 Apr 2024 12:06:47 +0200 Subject: [PATCH 046/110] Show wallet error toast from the top level --- dapp/src/components/Header/ConnectWallet.tsx | 5 +---- dapp/src/hooks/index.ts | 2 +- dapp/src/hooks/useInitApp.ts | 3 +++ .../hooks/{useWalletToast.ts => useShowWalletErrorToast.ts} | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) rename dapp/src/hooks/{useWalletToast.ts => useShowWalletErrorToast.ts} (96%) diff --git a/dapp/src/components/Header/ConnectWallet.tsx b/dapp/src/components/Header/ConnectWallet.tsx index fc60ca3d4..1a76f97c3 100644 --- a/dapp/src/components/Header/ConnectWallet.tsx +++ b/dapp/src/components/Header/ConnectWallet.tsx @@ -1,7 +1,7 @@ import React from "react" import { Button, HStack, Icon, Tooltip } from "@chakra-ui/react" import { Account } from "@ledgerhq/wallet-api-client" -import { useWalletToast, useWallet } from "#/hooks" +import { useWallet } from "#/hooks" import { CurrencyBalance } from "#/components/shared/CurrencyBalance" import { TextMd } from "#/components/shared/Typography" import { Bitcoin, EthereumIcon } from "#/assets/icons" @@ -31,9 +31,6 @@ export default function ConnectWallet() { ethereum: { account: ethAccount, requestAccount: requestEthereumAccount }, } = useWallet() - useWalletToast("ethereum") - useWalletToast("bitcoin") - const customDataBtcAccount = getCustomDataByAccount(btcAccount) const customDataEthAccount = getCustomDataByAccount(ethAccount) diff --git a/dapp/src/hooks/index.ts b/dapp/src/hooks/index.ts index 2a1408832..2ce001d3d 100644 --- a/dapp/src/hooks/index.ts +++ b/dapp/src/hooks/index.ts @@ -19,5 +19,5 @@ export * from "./useDepositTelemetry" export * from "./useFetchBTCPriceUSD" export * from "./useToast" export * from "./useWallet" -export * from "./useWalletToast" +export * from "./useShowWalletErrorToast" export * from "./useTimeout" diff --git a/dapp/src/hooks/useInitApp.ts b/dapp/src/hooks/useInitApp.ts index bfa07283e..91a62066c 100644 --- a/dapp/src/hooks/useInitApp.ts +++ b/dapp/src/hooks/useInitApp.ts @@ -1,6 +1,7 @@ import { useSentry } from "./sentry" import { useInitializeAcreSdk } from "./useInitializeAcreSdk" import { useFetchBTCPriceUSD } from "./useFetchBTCPriceUSD" +import { useShowWalletErrorToast } from "./useShowWalletErrorToast" export function useInitApp() { // TODO: Let's uncomment when dark mode is ready @@ -8,4 +9,6 @@ export function useInitApp() { useSentry() useInitializeAcreSdk() useFetchBTCPriceUSD() + useShowWalletErrorToast("ethereum") + useShowWalletErrorToast("bitcoin") } diff --git a/dapp/src/hooks/useWalletToast.ts b/dapp/src/hooks/useShowWalletErrorToast.ts similarity index 96% rename from dapp/src/hooks/useWalletToast.ts rename to dapp/src/hooks/useShowWalletErrorToast.ts index 9e01c2b37..610f50731 100644 --- a/dapp/src/hooks/useWalletToast.ts +++ b/dapp/src/hooks/useShowWalletErrorToast.ts @@ -11,7 +11,7 @@ const WALLET_ERROR_TOAST_ID = { ethereum: "ethereum-wallet-error", } -export function useWalletToast( +export function useShowWalletErrorToast( type: "bitcoin" | "ethereum", delay = ONE_SEC_IN_MILLISECONDS, ) { From 4c340232a87375e46594ae57574de6627a61909e Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 2 Apr 2024 13:02:26 +0200 Subject: [PATCH 047/110] Reorganizing toasts components Actually, defined toast components are not part of the shared components. Only the base component should be there. Let's update the file locations of these to the correct levels. --- .../ActiveStakingStep/DepositBTCModal.tsx | 6 +++--- .../DepositTransactionErrorToast.tsx | 19 +++++++++++++++++++ .../ActiveStakingStep/SignMessageModal.tsx | 6 ++---- .../SigningMessageErrorToast.tsx | 19 +++++++++++++++++++ .../{shared/toasts => }/WalletErrorToast.tsx | 13 +++++++++---- .../{alerts/ToastBase.tsx => Toast.tsx} | 13 ++++++++----- dapp/src/components/shared/alerts/index.ts | 1 - .../toasts/DepositTransactionErrorToast.tsx | 19 ------------------- .../toasts/MessageSigningErrorToast.tsx | 15 --------------- dapp/src/components/shared/toasts/index.ts | 3 --- dapp/src/hooks/useShowWalletErrorToast.ts | 9 +++------ 11 files changed, 63 insertions(+), 60 deletions(-) create mode 100644 dapp/src/components/TransactionModal/ActiveStakingStep/DepositTransactionErrorToast.tsx create mode 100644 dapp/src/components/TransactionModal/ActiveStakingStep/SigningMessageErrorToast.tsx rename dapp/src/components/{shared/toasts => }/WalletErrorToast.tsx (57%) rename dapp/src/components/shared/{alerts/ToastBase.tsx => Toast.tsx} (64%) delete mode 100644 dapp/src/components/shared/toasts/DepositTransactionErrorToast.tsx delete mode 100644 dapp/src/components/shared/toasts/MessageSigningErrorToast.tsx delete mode 100644 dapp/src/components/shared/toasts/index.ts diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index 649da9e3a..4308a5097 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -13,10 +13,10 @@ import { TextMd } from "#/components/shared/Typography" import { logPromiseFailure } from "#/utils" import { PROCESS_STATUSES } from "#/types" import { CardAlert } from "#/components/shared/alerts" -import { DepositTransactionErrorToast } from "#/components/shared/toasts" import StakingStepsModalContent from "./StakingStepsModalContent" - -const TOAST_ID = "deposit-transaction-error" +import DepositTransactionErrorToast, { + TOAST_ID, +} from "./DepositTransactionErrorToast" export default function DepositBTCModal() { const { ethAccount } = useWalletContext() diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositTransactionErrorToast.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositTransactionErrorToast.tsx new file mode 100644 index 000000000..79d5dfe39 --- /dev/null +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositTransactionErrorToast.tsx @@ -0,0 +1,19 @@ +import React from "react" +import Toast from "#/components/shared/Toast" + +export const TOAST_ID = "deposit-transaction-error" + +export default function DepositTransactionErrorToast({ + onClose, +}: { + onClose: () => void +}) { + return ( + + ) +} diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx index 7389990db..e3565a7a5 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx @@ -8,10 +8,8 @@ import { import { logPromiseFailure } from "#/utils" import { PROCESS_STATUSES } from "#/types" import { ReceiveSTBTCAlert } from "#/components/shared/alerts" -import { MessageSigningErrorToast } from "#/components/shared/toasts" import StakingStepsModalContent from "./StakingStepsModalContent" - -const TOAST_ID = "signing-error" +import SigningMessageErrorToast, { TOAST_ID } from "./SigningMessageErrorToast" export default function SignMessageModal() { const { goNext, setStatus } = useModalFlowContext() @@ -31,7 +29,7 @@ export default function SignMessageModal() { const onSignMessageError = useCallback(() => { openToast({ id: TOAST_ID, - render: MessageSigningErrorToast, + render: SigningMessageErrorToast, }) setButtonText("Try again") }, [openToast]) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SigningMessageErrorToast.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/SigningMessageErrorToast.tsx new file mode 100644 index 000000000..659a8d190 --- /dev/null +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/SigningMessageErrorToast.tsx @@ -0,0 +1,19 @@ +import React from "react" +import Toast from "#/components/shared/Toast" + +export const TOAST_ID = "signing-error" + +export default function SigningMessageErrorToast({ + onClose, +}: { + onClose: () => void +}) { + return ( + + ) +} diff --git a/dapp/src/components/shared/toasts/WalletErrorToast.tsx b/dapp/src/components/WalletErrorToast.tsx similarity index 57% rename from dapp/src/components/shared/toasts/WalletErrorToast.tsx rename to dapp/src/components/WalletErrorToast.tsx index 1d30869f8..dbac73f28 100644 --- a/dapp/src/components/shared/toasts/WalletErrorToast.tsx +++ b/dapp/src/components/WalletErrorToast.tsx @@ -1,8 +1,13 @@ import React from "react" import { Flex, Button } from "@chakra-ui/react" -import { ToastBase } from "../alerts" +import Toast from "./shared/Toast" -export function WalletErrorToast({ +export const WALLET_ERROR_TOAST_ID = { + bitcoin: "bitcoin-wallet-error", + ethereum: "ethereum-wallet-error", +} + +export default function WalletErrorToast({ title, onClick, onClose, @@ -12,12 +17,12 @@ export function WalletErrorToast({ onClose: () => void }) { return ( - + - + ) } diff --git a/dapp/src/components/shared/alerts/ToastBase.tsx b/dapp/src/components/shared/Toast.tsx similarity index 64% rename from dapp/src/components/shared/alerts/ToastBase.tsx rename to dapp/src/components/shared/Toast.tsx index 98cd45e6a..092163fa7 100644 --- a/dapp/src/components/shared/alerts/ToastBase.tsx +++ b/dapp/src/components/shared/Toast.tsx @@ -1,24 +1,27 @@ import React from "react" import { HStack } from "@chakra-ui/react" -import { Alert, AlertProps } from "./Alert" -import { TextSm } from "../Typography" +import { Alert, AlertProps } from "./alerts" +import { TextSm } from "./Typography" -type ToastBaseProps = { +type ToastProps = { title: string + subtitle?: string } & Omit & { onClose: () => void } -export function ToastBase({ +export default function Toast({ title, + subtitle, children, onClose, ...props -}: ToastBaseProps) { +}: ToastProps) { return ( {title} + {subtitle && {subtitle}} {children} diff --git a/dapp/src/components/shared/alerts/index.ts b/dapp/src/components/shared/alerts/index.ts index c9cbfceff..79555f74d 100644 --- a/dapp/src/components/shared/alerts/index.ts +++ b/dapp/src/components/shared/alerts/index.ts @@ -1,4 +1,3 @@ export * from "./Alert" export * from "./CardAlert" export * from "./ReceiveSTBTCAlert" -export * from "./ToastBase" diff --git a/dapp/src/components/shared/toasts/DepositTransactionErrorToast.tsx b/dapp/src/components/shared/toasts/DepositTransactionErrorToast.tsx deleted file mode 100644 index 59c9f2332..000000000 --- a/dapp/src/components/shared/toasts/DepositTransactionErrorToast.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import React from "react" -import { TextSm } from "../Typography" -import { ToastBase } from "../alerts" - -export function DepositTransactionErrorToast({ - onClose, -}: { - onClose: () => void -}) { - return ( - - Please try again. - - ) -} diff --git a/dapp/src/components/shared/toasts/MessageSigningErrorToast.tsx b/dapp/src/components/shared/toasts/MessageSigningErrorToast.tsx deleted file mode 100644 index c9bebd0ef..000000000 --- a/dapp/src/components/shared/toasts/MessageSigningErrorToast.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import React from "react" -import { TextSm } from "../Typography" -import { ToastBase } from "../alerts" - -export function MessageSigningErrorToast({ onClose }: { onClose: () => void }) { - return ( - - Please try again. - - ) -} diff --git a/dapp/src/components/shared/toasts/index.ts b/dapp/src/components/shared/toasts/index.ts deleted file mode 100644 index 9b997f38e..000000000 --- a/dapp/src/components/shared/toasts/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./MessageSigningErrorToast" -export * from "./DepositTransactionErrorToast" -export * from "./WalletErrorToast" diff --git a/dapp/src/hooks/useShowWalletErrorToast.ts b/dapp/src/hooks/useShowWalletErrorToast.ts index 610f50731..3bbbbbac7 100644 --- a/dapp/src/hooks/useShowWalletErrorToast.ts +++ b/dapp/src/hooks/useShowWalletErrorToast.ts @@ -1,16 +1,13 @@ import { useCallback, useEffect } from "react" import { ONE_SEC_IN_MILLISECONDS } from "#/constants" import { capitalizeFirstLetter, logPromiseFailure } from "#/utils" -import { WalletErrorToast } from "#/components/shared/toasts" +import WalletErrorToast, { + WALLET_ERROR_TOAST_ID, +} from "#/components/WalletErrorToast" import { useToast } from "./useToast" import { useWallet } from "./useWallet" import { useTimeout } from "./useTimeout" -const WALLET_ERROR_TOAST_ID = { - bitcoin: "bitcoin-wallet-error", - ethereum: "ethereum-wallet-error", -} - export function useShowWalletErrorToast( type: "bitcoin" | "ethereum", delay = ONE_SEC_IN_MILLISECONDS, From 976a466c49039be0e08c3dbd9bb73e3fdc7d01ea Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 2 Apr 2024 14:16:44 +0200 Subject: [PATCH 048/110] Add `@tabler/icons-react` package --- dapp/package.json | 1 + pnpm-lock.yaml | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/dapp/package.json b/dapp/package.json index f93626084..0504d3ed5 100644 --- a/dapp/package.json +++ b/dapp/package.json @@ -24,6 +24,7 @@ "@reduxjs/toolkit": "^2.2.0", "@sentry/react": "^7.98.0", "@sentry/types": "^7.102.0", + "@tabler/icons-react": "^3.1.0", "@tanstack/react-table": "^8.11.3", "axios": "^1.6.7", "ethers": "^6.10.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 055e028ec..60946e42d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -159,6 +159,9 @@ importers: '@sentry/types': specifier: ^7.102.0 version: 7.102.0 + '@tabler/icons-react': + specifier: ^3.1.0 + version: 3.1.0(react@18.2.0) '@tanstack/react-table': specifier: ^8.11.3 version: 8.11.7(react-dom@18.2.0)(react@18.2.0) @@ -6430,6 +6433,19 @@ packages: dependencies: defer-to-connect: 2.0.1 + /@tabler/icons-react@3.1.0(react@18.2.0): + resolution: {integrity: sha512-k/WTlax2vbj/LpxvaJ+BmaLAAhVUgyLj4Ftgaczz66tUSNzqrAZXCFdOU7cRMYPNVBqyqE2IdQd2rzzhDEJvkw==} + peerDependencies: + react: '>= 16' + dependencies: + '@tabler/icons': 3.1.0 + react: 18.2.0 + dev: false + + /@tabler/icons@3.1.0: + resolution: {integrity: sha512-CpZGyS1IVJKFcv88yZ2sYZIpWWhQ6oy76BQKQ5SF0fGgOqgyqKdBGG/YGyyMW632on37MX7VqQIMTzN/uQqmFg==} + dev: false + /@tanstack/react-table@8.11.7(react-dom@18.2.0)(react@18.2.0): resolution: {integrity: sha512-ZbzfMkLjxUTzNPBXJYH38pv2VpC9WUA+Qe5USSHEBz0dysDTv4z/ARI3csOed/5gmlmrPzVUN3UXGuUMbod3Jg==} engines: {node: '>=12'} From 39850ceb5ea4557c0ff5f10641b73ce0ec4935a3 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 2 Apr 2024 14:21:34 +0200 Subject: [PATCH 049/110] Use icons for alert from `@tabler/icons-react` --- dapp/src/assets/icons/AlertError.tsx | 17 ----------------- dapp/src/assets/icons/AlertInfo.tsx | 17 ----------------- dapp/src/assets/icons/index.ts | 2 -- .../shared/TokenBalanceInput/index.tsx | 4 ++-- dapp/src/components/shared/alerts/Alert.tsx | 9 ++++----- 5 files changed, 6 insertions(+), 43 deletions(-) delete mode 100644 dapp/src/assets/icons/AlertError.tsx delete mode 100644 dapp/src/assets/icons/AlertInfo.tsx diff --git a/dapp/src/assets/icons/AlertError.tsx b/dapp/src/assets/icons/AlertError.tsx deleted file mode 100644 index 6fb513e5b..000000000 --- a/dapp/src/assets/icons/AlertError.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import React from "react" -import { createIcon } from "@chakra-ui/react" - -export const AlertError = createIcon({ - displayName: "AlertError", - viewBox: "0 0 24 25", - path: [ - , - ], -}) diff --git a/dapp/src/assets/icons/AlertInfo.tsx b/dapp/src/assets/icons/AlertInfo.tsx deleted file mode 100644 index 2eda75539..000000000 --- a/dapp/src/assets/icons/AlertInfo.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import React from "react" -import { createIcon } from "@chakra-ui/react" - -export const AlertInfo = createIcon({ - displayName: "AlertInfo", - viewBox: "0 0 24 24", - path: [ - , - ], -}) diff --git a/dapp/src/assets/icons/index.ts b/dapp/src/assets/icons/index.ts index 5be87f41a..f6931b182 100644 --- a/dapp/src/assets/icons/index.ts +++ b/dapp/src/assets/icons/index.ts @@ -7,8 +7,6 @@ export * from "./ArrowRight" export * from "./AcreLogo" export * from "./ConnectBTCAccount" export * from "./ConnectETHAccount" -export * from "./AlertInfo" -export * from "./AlertError" export * from "./stBTC" export * from "./BTC" export * from "./ShieldPlus" diff --git a/dapp/src/components/shared/TokenBalanceInput/index.tsx b/dapp/src/components/shared/TokenBalanceInput/index.tsx index de55b64dd..f502bd3b1 100644 --- a/dapp/src/components/shared/TokenBalanceInput/index.tsx +++ b/dapp/src/components/shared/TokenBalanceInput/index.tsx @@ -17,8 +17,8 @@ import { getCurrencyByType, userAmountToBigInt, } from "#/utils" -import { AlertInfo } from "#/assets/icons" import { CurrencyType } from "#/types" +import { IconInfoCircle } from "@tabler/icons-react" import NumberFormatInput, { NumberFormatInputValues, } from "../NumberFormatInput" @@ -48,7 +48,7 @@ function HelperErrorText({ if (helperText) { return ( - + {helperText} ) diff --git a/dapp/src/components/shared/alerts/Alert.tsx b/dapp/src/components/shared/alerts/Alert.tsx index 7f06f2201..b22f08562 100644 --- a/dapp/src/components/shared/alerts/Alert.tsx +++ b/dapp/src/components/shared/alerts/Alert.tsx @@ -1,17 +1,16 @@ import React from "react" import { Alert as ChakraAlert, - AlertIcon, AlertProps as ChakraAlertProps, Icon, CloseButton, HStack, } from "@chakra-ui/react" -import { AlertError, AlertInfo } from "#/assets/icons" +import { IconInfoCircle, IconExclamationCircle } from "@tabler/icons-react" const ICONS = { - info: AlertInfo, - error: AlertError, + info: IconInfoCircle, + error: IconExclamationCircle, } type AlertStatus = keyof typeof ICONS @@ -37,7 +36,7 @@ export function Alert({ return ( {withIcon && status && ( - + )} {children} From 1107ecfa1d3a3720664ef2260c7c4d41eef1e35b Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Mon, 8 Apr 2024 13:50:31 +0200 Subject: [PATCH 050/110] Create a special hook for init global toasts --- dapp/src/hooks/index.ts | 3 +-- dapp/src/hooks/toasts/index.ts | 3 +++ dapp/src/hooks/toasts/useInitGlobalToasts.ts | 6 ++++++ dapp/src/hooks/{ => toasts}/useShowWalletErrorToast.ts | 4 ++-- dapp/src/hooks/{ => toasts}/useToast.ts | 0 dapp/src/hooks/useInitApp.ts | 5 ++--- 6 files changed, 14 insertions(+), 7 deletions(-) create mode 100644 dapp/src/hooks/toasts/index.ts create mode 100644 dapp/src/hooks/toasts/useInitGlobalToasts.ts rename dapp/src/hooks/{ => toasts}/useShowWalletErrorToast.ts (93%) rename dapp/src/hooks/{ => toasts}/useToast.ts (100%) diff --git a/dapp/src/hooks/index.ts b/dapp/src/hooks/index.ts index 7d3c2a063..08821f731 100644 --- a/dapp/src/hooks/index.ts +++ b/dapp/src/hooks/index.ts @@ -1,4 +1,5 @@ export * from "./store" +export * from "./toasts" export * from "./useDetectThemeMode" export * from "./useRequestBitcoinAccount" export * from "./useRequestEthereumAccount" @@ -17,8 +18,6 @@ export * from "./useInitApp" export * from "./useCurrencyConversion" export * from "./useDepositTelemetry" export * from "./useFetchBTCPriceUSD" -export * from "./useToast" export * from "./useWallet" -export * from "./useShowWalletErrorToast" export * from "./useTimeout" export * from "./useSize" diff --git a/dapp/src/hooks/toasts/index.ts b/dapp/src/hooks/toasts/index.ts new file mode 100644 index 000000000..c9a093219 --- /dev/null +++ b/dapp/src/hooks/toasts/index.ts @@ -0,0 +1,3 @@ +export * from "./useInitGlobalToasts" +export * from "./useShowWalletErrorToast" +export * from "./useToast" diff --git a/dapp/src/hooks/toasts/useInitGlobalToasts.ts b/dapp/src/hooks/toasts/useInitGlobalToasts.ts new file mode 100644 index 000000000..0fec6ef12 --- /dev/null +++ b/dapp/src/hooks/toasts/useInitGlobalToasts.ts @@ -0,0 +1,6 @@ +import { useShowWalletErrorToast } from "./useShowWalletErrorToast" + +export function useInitGlobalToasts() { + useShowWalletErrorToast("ethereum") + useShowWalletErrorToast("bitcoin") +} diff --git a/dapp/src/hooks/useShowWalletErrorToast.ts b/dapp/src/hooks/toasts/useShowWalletErrorToast.ts similarity index 93% rename from dapp/src/hooks/useShowWalletErrorToast.ts rename to dapp/src/hooks/toasts/useShowWalletErrorToast.ts index 3bbbbbac7..ae7f89922 100644 --- a/dapp/src/hooks/useShowWalletErrorToast.ts +++ b/dapp/src/hooks/toasts/useShowWalletErrorToast.ts @@ -5,8 +5,8 @@ import WalletErrorToast, { WALLET_ERROR_TOAST_ID, } from "#/components/WalletErrorToast" import { useToast } from "./useToast" -import { useWallet } from "./useWallet" -import { useTimeout } from "./useTimeout" +import { useWallet } from "../useWallet" +import { useTimeout } from "../useTimeout" export function useShowWalletErrorToast( type: "bitcoin" | "ethereum", diff --git a/dapp/src/hooks/useToast.ts b/dapp/src/hooks/toasts/useToast.ts similarity index 100% rename from dapp/src/hooks/useToast.ts rename to dapp/src/hooks/toasts/useToast.ts diff --git a/dapp/src/hooks/useInitApp.ts b/dapp/src/hooks/useInitApp.ts index 91a62066c..e559e6df4 100644 --- a/dapp/src/hooks/useInitApp.ts +++ b/dapp/src/hooks/useInitApp.ts @@ -1,7 +1,7 @@ import { useSentry } from "./sentry" import { useInitializeAcreSdk } from "./useInitializeAcreSdk" import { useFetchBTCPriceUSD } from "./useFetchBTCPriceUSD" -import { useShowWalletErrorToast } from "./useShowWalletErrorToast" +import { useInitGlobalToasts } from "./toasts/useInitGlobalToasts" export function useInitApp() { // TODO: Let's uncomment when dark mode is ready @@ -9,6 +9,5 @@ export function useInitApp() { useSentry() useInitializeAcreSdk() useFetchBTCPriceUSD() - useShowWalletErrorToast("ethereum") - useShowWalletErrorToast("bitcoin") + useInitGlobalToasts() } From 07b035f20dbd0fcb2f755be49e33654ab33e1dde Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Mon, 8 Apr 2024 14:15:01 +0200 Subject: [PATCH 051/110] Rename methods for `useToast` --- .../ActiveStakingStep/DepositBTCModal.tsx | 2 +- .../ActiveStakingStep/SignMessageModal.tsx | 2 +- .../src/hooks/toasts/useShowWalletErrorToast.ts | 10 +++++----- dapp/src/hooks/toasts/useToast.ts | 17 +++++++++-------- 4 files changed, 16 insertions(+), 15 deletions(-) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index 4308a5097..dc8424ae0 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -24,7 +24,7 @@ export default function DepositBTCModal() { const { setStatus } = useModalFlowContext() const { btcAddress, depositReceipt, stake } = useStakeFlowContext() const depositTelemetry = useDepositTelemetry() - const { close: closeToast, open: openToast } = useToast() + const { closeToast, openToast } = useToast() const [isLoading, setIsLoading] = useState(false) const [buttonText, setButtonText] = useState("Deposit BTC") diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx index e3565a7a5..6c8d5bba0 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx @@ -15,7 +15,7 @@ export default function SignMessageModal() { const { goNext, setStatus } = useModalFlowContext() const { signMessage } = useStakeFlowContext() const [buttonText, setButtonText] = useState("Sign now") - const { close: closeToast, open: openToast } = useToast() + const { closeToast, openToast } = useToast() useEffect(() => { setStatus(PROCESS_STATUSES.PENDING) diff --git a/dapp/src/hooks/toasts/useShowWalletErrorToast.ts b/dapp/src/hooks/toasts/useShowWalletErrorToast.ts index ae7f89922..33ed0e53f 100644 --- a/dapp/src/hooks/toasts/useShowWalletErrorToast.ts +++ b/dapp/src/hooks/toasts/useShowWalletErrorToast.ts @@ -15,7 +15,7 @@ export function useShowWalletErrorToast( const { [type]: { account, requestAccount }, } = useWallet() - const { close, open } = useToast() + const { closeToast, openToast } = useToast() const toastId = WALLET_ERROR_TOAST_ID[type] @@ -26,7 +26,7 @@ export function useShowWalletErrorToast( const handleOpen = useCallback( () => - open({ + openToast({ id: toastId, render: ({ onClose }) => WalletErrorToast({ @@ -35,7 +35,7 @@ export function useShowWalletErrorToast( onClick: handleConnect, }), }), - [handleConnect, open, toastId, type], + [handleConnect, openToast, toastId, type], ) useTimeout(handleOpen, delay) @@ -43,6 +43,6 @@ export function useShowWalletErrorToast( useEffect(() => { if (!account) return - close(toastId) - }, [account, close, toastId]) + closeToast(toastId) + }, [account, closeToast, toastId]) } diff --git a/dapp/src/hooks/toasts/useToast.ts b/dapp/src/hooks/toasts/useToast.ts index 60dbee49d..b38f1e098 100644 --- a/dapp/src/hooks/toasts/useToast.ts +++ b/dapp/src/hooks/toasts/useToast.ts @@ -16,7 +16,7 @@ export function useToast() { [toast], ) - const open = useCallback( + const openToast = useCallback( ({ id, ...options }: UseToastOptions) => { if (!id) { overriddenToast(options) @@ -30,11 +30,12 @@ export function useToast() { [overriddenToast, toast], ) - return useMemo( - () => ({ - ...Object.assign(overriddenToast, toast), - open, - }), - [overriddenToast, toast, open], - ) + return useMemo(() => { + const { close: closeToast, ...rest } = Object.assign(overriddenToast, toast) + return { + ...rest, + openToast, + closeToast, + } + }, [overriddenToast, toast, openToast]) } From 6fc58a31f00d598877f0afbe4a093343c14eb5c9 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Mon, 8 Apr 2024 16:09:36 +0200 Subject: [PATCH 052/110] Save the toast id globally along with the correct component --- .../ActiveStakingStep/DepositBTCModal.tsx | 12 +++++--- .../ActiveStakingStep/SignMessageModal.tsx | 8 +++-- .../DepositTransactionErrorToast.tsx | 6 ++-- .../SigningMessageErrorToast.tsx | 10 ++----- .../{ => toasts}/WalletErrorToast.tsx | 9 ++---- dapp/src/components/toasts/index.ts | 3 ++ .../hooks/toasts/useShowWalletErrorToast.ts | 29 +++++++++++++------ dapp/src/types/index.ts | 1 + dapp/src/types/toast.ts | 23 +++++++++++++++ 9 files changed, 66 insertions(+), 35 deletions(-) rename dapp/src/components/{TransactionModal/ActiveStakingStep => toasts}/DepositTransactionErrorToast.tsx (61%) rename dapp/src/components/{TransactionModal/ActiveStakingStep => toasts}/SigningMessageErrorToast.tsx (50%) rename dapp/src/components/{ => toasts}/WalletErrorToast.tsx (70%) create mode 100644 dapp/src/components/toasts/index.ts create mode 100644 dapp/src/types/toast.ts diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx index dc8424ae0..d2e7d87b5 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/DepositBTCModal.tsx @@ -13,10 +13,11 @@ import { TextMd } from "#/components/shared/Typography" import { logPromiseFailure } from "#/utils" import { PROCESS_STATUSES } from "#/types" import { CardAlert } from "#/components/shared/alerts" +import { TOASTS, TOAST_IDS } from "#/types/toast" import StakingStepsModalContent from "./StakingStepsModalContent" -import DepositTransactionErrorToast, { - TOAST_ID, -} from "./DepositTransactionErrorToast" + +const TOAST_ID = TOAST_IDS.DEPOSIT_TRANSACTION_ERROR +const TOAST = TOASTS[TOAST_ID] export default function DepositBTCModal() { const { ethAccount } = useWalletContext() @@ -53,7 +54,10 @@ export default function DepositBTCModal() { }, [closeToast, setStatus, handleStake]) const showError = useCallback(() => { - openToast({ id: TOAST_ID, render: DepositTransactionErrorToast }) + openToast({ + id: TOAST_ID, + render: TOAST, + }) setButtonText("Try again") }, [openToast]) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx index 6c8d5bba0..37bba6883 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/SignMessageModal.tsx @@ -6,10 +6,12 @@ import { useToast, } from "#/hooks" import { logPromiseFailure } from "#/utils" -import { PROCESS_STATUSES } from "#/types" +import { PROCESS_STATUSES, TOASTS, TOAST_IDS } from "#/types" import { ReceiveSTBTCAlert } from "#/components/shared/alerts" import StakingStepsModalContent from "./StakingStepsModalContent" -import SigningMessageErrorToast, { TOAST_ID } from "./SigningMessageErrorToast" + +const TOAST_ID = TOAST_IDS.SIGNING_ERROR +const TOAST = TOASTS[TOAST_ID] export default function SignMessageModal() { const { goNext, setStatus } = useModalFlowContext() @@ -29,7 +31,7 @@ export default function SignMessageModal() { const onSignMessageError = useCallback(() => { openToast({ id: TOAST_ID, - render: SigningMessageErrorToast, + render: TOAST, }) setButtonText("Try again") }, [openToast]) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositTransactionErrorToast.tsx b/dapp/src/components/toasts/DepositTransactionErrorToast.tsx similarity index 61% rename from dapp/src/components/TransactionModal/ActiveStakingStep/DepositTransactionErrorToast.tsx rename to dapp/src/components/toasts/DepositTransactionErrorToast.tsx index 79d5dfe39..6a2dce775 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/DepositTransactionErrorToast.tsx +++ b/dapp/src/components/toasts/DepositTransactionErrorToast.tsx @@ -1,9 +1,7 @@ import React from "react" -import Toast from "#/components/shared/Toast" +import Toast from "../shared/Toast" -export const TOAST_ID = "deposit-transaction-error" - -export default function DepositTransactionErrorToast({ +export function DepositTransactionErrorToast({ onClose, }: { onClose: () => void diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/SigningMessageErrorToast.tsx b/dapp/src/components/toasts/SigningMessageErrorToast.tsx similarity index 50% rename from dapp/src/components/TransactionModal/ActiveStakingStep/SigningMessageErrorToast.tsx rename to dapp/src/components/toasts/SigningMessageErrorToast.tsx index 659a8d190..2b22cbb1a 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/SigningMessageErrorToast.tsx +++ b/dapp/src/components/toasts/SigningMessageErrorToast.tsx @@ -1,13 +1,7 @@ import React from "react" -import Toast from "#/components/shared/Toast" +import Toast from "../shared/Toast" -export const TOAST_ID = "signing-error" - -export default function SigningMessageErrorToast({ - onClose, -}: { - onClose: () => void -}) { +export function SigningMessageErrorToast({ onClose }: { onClose: () => void }) { return ( logPromiseFailure(requestAccount()), @@ -27,15 +38,15 @@ export function useShowWalletErrorToast( const handleOpen = useCallback( () => openToast({ - id: toastId, + id, render: ({ onClose }) => - WalletErrorToast({ + Component({ title: capitalizeFirstLetter(`${type} wallet is not connected`), onClose, onClick: handleConnect, }), }), - [handleConnect, openToast, toastId, type], + [Component, handleConnect, id, openToast, type], ) useTimeout(handleOpen, delay) @@ -43,6 +54,6 @@ export function useShowWalletErrorToast( useEffect(() => { if (!account) return - closeToast(toastId) - }, [account, closeToast, toastId]) + closeToast(id) + }, [account, closeToast, id]) } diff --git a/dapp/src/types/index.ts b/dapp/src/types/index.ts index 53aaf17ed..f36accc9c 100644 --- a/dapp/src/types/index.ts +++ b/dapp/src/types/index.ts @@ -11,3 +11,4 @@ export * from "./charts" export * from "./activity" export * from "./coingecko" export * from "./size" +export * from "./toast" diff --git a/dapp/src/types/toast.ts b/dapp/src/types/toast.ts new file mode 100644 index 000000000..c4a3fe962 --- /dev/null +++ b/dapp/src/types/toast.ts @@ -0,0 +1,23 @@ +import { ReactNode } from "react" +import { + DepositTransactionErrorToast, + SigningMessageErrorToast, + WalletErrorToast, +} from "#/components/toasts" + +export const TOAST_IDS = { + BITCOIN_WALLET_ERROR: "bitcoin-wallet-error", + ETHEREUM_WALLET_ERROR: "ethereum-wallet-error", + SIGNING_ERROR: "signing-error", + DEPOSIT_TRANSACTION_ERROR: "deposit-transaction-error", +} as const + +export type ToastID = (typeof TOAST_IDS)[keyof typeof TOAST_IDS] + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export const TOASTS: Record ReactNode> = { + [TOAST_IDS.BITCOIN_WALLET_ERROR]: WalletErrorToast, + [TOAST_IDS.ETHEREUM_WALLET_ERROR]: WalletErrorToast, + [TOAST_IDS.SIGNING_ERROR]: SigningMessageErrorToast, + [TOAST_IDS.DEPOSIT_TRANSACTION_ERROR]: DepositTransactionErrorToast, +} From 3766428f339226f23721dec01ecb755d06341cf3 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 9 Apr 2024 12:17:49 +0200 Subject: [PATCH 053/110] Rename from `minDepositAmount` to `minStakeAmount` --- .../ActiveStakingStep/StakeFormModal/index.tsx | 8 ++++---- .../ActiveUnstakingStep/UnstakeFormModal/index.tsx | 6 +++--- dapp/src/hooks/sdk/index.ts | 2 +- ...MinDepositAmount.ts => useFetchMinStakeAmount.ts} | 12 ++++++------ dapp/src/hooks/sdk/useFetchSdkData.ts | 4 ++-- dapp/src/store/btc/btcSelector.ts | 4 ++-- dapp/src/store/btc/btcSlice.ts | 10 +++++----- 7 files changed, 23 insertions(+), 23 deletions(-) rename dapp/src/hooks/sdk/{useFetchMinDepositAmount.ts => useFetchMinStakeAmount.ts} (60%) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx index d7afc24cf..563099b0f 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx @@ -3,7 +3,7 @@ import TokenAmountForm from "#/components/shared/TokenAmountForm" import { TokenAmountFormValues } from "#/components/shared/TokenAmountForm/TokenAmountFormBase" import { useAppSelector, useWalletContext } from "#/hooks" import { FormSubmitButton } from "#/components/shared/Form" -import { selectMinDepositAmount } from "#/store/btc" +import { selectMinStakeAmount } from "#/store/btc" import StakeDetails from "./StakeDetails" function StakeFormModal({ @@ -11,7 +11,7 @@ function StakeFormModal({ }: { onSubmitForm: (values: TokenAmountFormValues) => void }) { - const minDepositAmount = useAppSelector(selectMinDepositAmount) + const minStakeAmount = useAppSelector(selectMinStakeAmount) const { btcAccount } = useWalletContext() const tokenBalance = btcAccount?.balance.toString() ?? "0" @@ -20,12 +20,12 @@ function StakeFormModal({ tokenBalanceInputPlaceholder="BTC" currency="bitcoin" tokenBalance={tokenBalance} - minTokenAmount={minDepositAmount} + minTokenAmount={minStakeAmount} onSubmitForm={onSubmitForm} > Stake diff --git a/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx index 561ec08eb..19b3cc115 100644 --- a/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx @@ -6,7 +6,7 @@ import { TextMd, TextSm } from "#/components/shared/Typography" import Spinner from "#/components/shared/Spinner" import { FormSubmitButton } from "#/components/shared/Form" import { useAppSelector } from "#/hooks" -import { selectMinDepositAmount } from "#/store/btc" +import { selectMinStakeAmount } from "#/store/btc" import UnstakeDetails from "./UnstakeDetails" // TODO: Use a position amount @@ -17,14 +17,14 @@ function UnstakeFormModal({ }: { onSubmitForm: (values: TokenAmountFormValues) => void }) { - const minDepositAmount = useAppSelector(selectMinDepositAmount) + const minStakeAmount = useAppSelector(selectMinStakeAmount) return ( diff --git a/dapp/src/hooks/sdk/index.ts b/dapp/src/hooks/sdk/index.ts index 73d11a6c9..11c585517 100644 --- a/dapp/src/hooks/sdk/index.ts +++ b/dapp/src/hooks/sdk/index.ts @@ -1,3 +1,3 @@ export * from "./useInitializeAcreSdk" -export * from "./useFetchMinDepositAmount" +export * from "./useFetchMinStakeAmount" export * from "./useFetchSdkData" diff --git a/dapp/src/hooks/sdk/useFetchMinDepositAmount.ts b/dapp/src/hooks/sdk/useFetchMinStakeAmount.ts similarity index 60% rename from dapp/src/hooks/sdk/useFetchMinDepositAmount.ts rename to dapp/src/hooks/sdk/useFetchMinStakeAmount.ts index b9354890f..9a2fe7972 100644 --- a/dapp/src/hooks/sdk/useFetchMinDepositAmount.ts +++ b/dapp/src/hooks/sdk/useFetchMinStakeAmount.ts @@ -1,25 +1,25 @@ import { useEffect } from "react" -import { setMinDepositAmount } from "#/store/btc" +import { setMinStakeAmount } from "#/store/btc" import { logPromiseFailure } from "#/utils" import { useAcreContext } from "#/acre-react/hooks" import { useAppDispatch } from "../store/useAppDispatch" -export function useFetchMinDepositAmount() { +export function useFetchMinStakeAmount() { const { acre, isInitialized } = useAcreContext() const dispatch = useAppDispatch() useEffect(() => { if (!isInitialized || !acre) return - const fetchMinDepositAmount = async () => { + const fetchMinStakeAmount = async () => { // TODO: Use function from SDK - const minDepositAmount = await new Promise((resolve) => { + const minStakeAmount = await new Promise((resolve) => { resolve(BigInt(String(1e4))) // 0.0001 BTC }) - dispatch(setMinDepositAmount(minDepositAmount)) + dispatch(setMinStakeAmount(minStakeAmount)) } - logPromiseFailure(fetchMinDepositAmount()) + logPromiseFailure(fetchMinStakeAmount()) }, [acre, dispatch, isInitialized]) } diff --git a/dapp/src/hooks/sdk/useFetchSdkData.ts b/dapp/src/hooks/sdk/useFetchSdkData.ts index 083619881..d2c2ea7cd 100644 --- a/dapp/src/hooks/sdk/useFetchSdkData.ts +++ b/dapp/src/hooks/sdk/useFetchSdkData.ts @@ -1,5 +1,5 @@ -import { useFetchMinDepositAmount } from "./useFetchMinDepositAmount" +import { useFetchMinStakeAmount } from "./useFetchMinStakeAmount" export function useFetchSdkData() { - useFetchMinDepositAmount() + useFetchMinStakeAmount() } diff --git a/dapp/src/store/btc/btcSelector.ts b/dapp/src/store/btc/btcSelector.ts index 88a511361..058fccca7 100644 --- a/dapp/src/store/btc/btcSelector.ts +++ b/dapp/src/store/btc/btcSelector.ts @@ -9,5 +9,5 @@ export const selectSharesBalance = (state: RootState): bigint => export const selectBtcUsdPrice = (state: RootState): number => state.btc.usdPrice -export const selectMinDepositAmount = (state: RootState) => - state.btc.minDepositAmount +export const selectMinStakeAmount = (state: RootState) => + state.btc.minStakeAmount diff --git a/dapp/src/store/btc/btcSlice.ts b/dapp/src/store/btc/btcSlice.ts index 0f69fb13e..617995479 100644 --- a/dapp/src/store/btc/btcSlice.ts +++ b/dapp/src/store/btc/btcSlice.ts @@ -6,7 +6,7 @@ type BtcState = { sharesBalance: bigint isLoadingPriceUSD: boolean usdPrice: number - minDepositAmount: bigint + minStakeAmount: bigint } const initialState: BtcState = { @@ -14,7 +14,7 @@ const initialState: BtcState = { sharesBalance: 0n, isLoadingPriceUSD: false, usdPrice: 0, - minDepositAmount: 0n, + minStakeAmount: 0n, } // Store Bitcoin data such as balance, balance in usd and other related data to Bitcoin chain. @@ -28,8 +28,8 @@ export const btcSlice = createSlice({ setEstimatedBtcBalance(state, action: PayloadAction) { state.estimatedBtcBalance = action.payload }, - setMinDepositAmount(state, action: PayloadAction) { - state.minDepositAmount = action.payload + setMinStakeAmount(state, action: PayloadAction) { + state.minStakeAmount = action.payload }, }, extraReducers: (builder) => { @@ -49,5 +49,5 @@ export const btcSlice = createSlice({ }, }) -export const { setSharesBalance, setEstimatedBtcBalance, setMinDepositAmount } = +export const { setSharesBalance, setEstimatedBtcBalance, setMinStakeAmount } = btcSlice.actions From 45d58fd9d2f56ed90c4e1c0673af07e8c2a0f7c0 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 9 Apr 2024 12:23:10 +0200 Subject: [PATCH 054/110] Move `useFetchBTCBalance` to `useFetchSdkData` --- dapp/src/hooks/index.ts | 1 - dapp/src/hooks/sdk/index.ts | 1 + dapp/src/hooks/{ => sdk}/useFetchBTCBalance.ts | 4 ++-- dapp/src/hooks/sdk/useFetchSdkData.ts | 2 ++ dapp/src/hooks/useInitApp.ts | 2 -- 5 files changed, 5 insertions(+), 5 deletions(-) rename dapp/src/hooks/{ => sdk}/useFetchBTCBalance.ts (89%) diff --git a/dapp/src/hooks/index.ts b/dapp/src/hooks/index.ts index afdc0dd90..e825510f0 100644 --- a/dapp/src/hooks/index.ts +++ b/dapp/src/hooks/index.ts @@ -17,5 +17,4 @@ export * from "./useInitApp" export * from "./useCurrencyConversion" export * from "./useDepositTelemetry" export * from "./useFetchBTCPriceUSD" -export * from "./useFetchBTCBalance" export * from "./useSize" diff --git a/dapp/src/hooks/sdk/index.ts b/dapp/src/hooks/sdk/index.ts index 11c585517..ffac77cf2 100644 --- a/dapp/src/hooks/sdk/index.ts +++ b/dapp/src/hooks/sdk/index.ts @@ -1,3 +1,4 @@ export * from "./useInitializeAcreSdk" export * from "./useFetchMinStakeAmount" export * from "./useFetchSdkData" +export * from "./useFetchBTCBalance" diff --git a/dapp/src/hooks/useFetchBTCBalance.ts b/dapp/src/hooks/sdk/useFetchBTCBalance.ts similarity index 89% rename from dapp/src/hooks/useFetchBTCBalance.ts rename to dapp/src/hooks/sdk/useFetchBTCBalance.ts index 360135312..ab73285d3 100644 --- a/dapp/src/hooks/useFetchBTCBalance.ts +++ b/dapp/src/hooks/sdk/useFetchBTCBalance.ts @@ -3,8 +3,8 @@ import { EthereumAddress } from "@acre-btc/sdk" import { useAcreContext } from "#/acre-react/hooks" import { logPromiseFailure } from "#/utils" import { setEstimatedBtcBalance, setSharesBalance } from "#/store/btc" -import { useWalletContext } from "./useWalletContext" -import { useAppDispatch } from "./store" +import { useWalletContext } from "../useWalletContext" +import { useAppDispatch } from "../store/useAppDispatch" export function useFetchBTCBalance() { const { acre, isInitialized } = useAcreContext() diff --git a/dapp/src/hooks/sdk/useFetchSdkData.ts b/dapp/src/hooks/sdk/useFetchSdkData.ts index d2c2ea7cd..375a50db4 100644 --- a/dapp/src/hooks/sdk/useFetchSdkData.ts +++ b/dapp/src/hooks/sdk/useFetchSdkData.ts @@ -1,5 +1,7 @@ +import { useFetchBTCBalance } from "./useFetchBTCBalance" import { useFetchMinStakeAmount } from "./useFetchMinStakeAmount" export function useFetchSdkData() { + useFetchBTCBalance() useFetchMinStakeAmount() } diff --git a/dapp/src/hooks/useInitApp.ts b/dapp/src/hooks/useInitApp.ts index 65ba5b7f7..7065f102b 100644 --- a/dapp/src/hooks/useInitApp.ts +++ b/dapp/src/hooks/useInitApp.ts @@ -1,7 +1,6 @@ import { useFetchSdkData, useInitializeAcreSdk } from "./sdk" import { useSentry } from "./sentry" import { useFetchBTCPriceUSD } from "./useFetchBTCPriceUSD" -import { useFetchBTCBalance } from "./useFetchBTCBalance" export function useInitApp() { // TODO: Let's uncomment when dark mode is ready @@ -10,5 +9,4 @@ export function useInitApp() { useInitializeAcreSdk() useFetchSdkData() useFetchBTCPriceUSD() - useFetchBTCBalance() } From 88f96d8569c7f4a120bd4df20ee48a8da251f313 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 9 Apr 2024 12:29:48 +0200 Subject: [PATCH 055/110] Create a hook for min stake amount --- .../ActiveStakingStep/StakeFormModal/index.tsx | 5 ++--- dapp/src/hooks/store/index.ts | 1 + dapp/src/hooks/store/useMinStakeAmount.ts | 6 ++++++ 3 files changed, 9 insertions(+), 3 deletions(-) create mode 100644 dapp/src/hooks/store/useMinStakeAmount.ts diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx index 563099b0f..70a03a732 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx @@ -1,9 +1,8 @@ import React from "react" import TokenAmountForm from "#/components/shared/TokenAmountForm" import { TokenAmountFormValues } from "#/components/shared/TokenAmountForm/TokenAmountFormBase" -import { useAppSelector, useWalletContext } from "#/hooks" +import { useMinStakeAmount, useWalletContext } from "#/hooks" import { FormSubmitButton } from "#/components/shared/Form" -import { selectMinStakeAmount } from "#/store/btc" import StakeDetails from "./StakeDetails" function StakeFormModal({ @@ -11,7 +10,7 @@ function StakeFormModal({ }: { onSubmitForm: (values: TokenAmountFormValues) => void }) { - const minStakeAmount = useAppSelector(selectMinStakeAmount) + const minStakeAmount = useMinStakeAmount() const { btcAccount } = useWalletContext() const tokenBalance = btcAccount?.balance.toString() ?? "0" diff --git a/dapp/src/hooks/store/index.ts b/dapp/src/hooks/store/index.ts index ac22e8a41..f34e76947 100644 --- a/dapp/src/hooks/store/index.ts +++ b/dapp/src/hooks/store/index.ts @@ -2,3 +2,4 @@ export * from "./useAppDispatch" export * from "./useAppSelector" export * from "./useEstimatedBTCBalance" export * from "./useSharesBalance" +export * from "./useMinStakeAmount" diff --git a/dapp/src/hooks/store/useMinStakeAmount.ts b/dapp/src/hooks/store/useMinStakeAmount.ts new file mode 100644 index 000000000..96cde88d6 --- /dev/null +++ b/dapp/src/hooks/store/useMinStakeAmount.ts @@ -0,0 +1,6 @@ +import { selectMinStakeAmount } from "#/store/btc" +import { useAppSelector } from "./useAppSelector" + +export function useMinStakeAmount() { + return useAppSelector(selectMinStakeAmount) +} From d7884f804e91e3f78a0358f4ea5fa45b4708c66f Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 9 Apr 2024 14:10:30 +0200 Subject: [PATCH 056/110] Add `fromSatoshi` and `toSatoshi` to utils function Add `fromSatoshi` fn that converts an amount from `1e8` to `1e18` token precision. Also here we remove optional `fromPrecision` param in `toSatoshi` fn - we assume we always convert from `1e18` to `1e8` and in `fromSatoshi` we always convert from `1e8` to `1e18`. --- sdk/src/lib/utils/index.ts | 1 + sdk/src/lib/utils/satoshi-converter.ts | 15 +++++++++++++++ 2 files changed, 16 insertions(+) create mode 100644 sdk/src/lib/utils/satoshi-converter.ts diff --git a/sdk/src/lib/utils/index.ts b/sdk/src/lib/utils/index.ts index 294cd1874..70c6b147c 100644 --- a/sdk/src/lib/utils/index.ts +++ b/sdk/src/lib/utils/index.ts @@ -1,3 +1,4 @@ export * from "./hex" export * from "./ethereum-signer" export * from "./backoff" +export * from "./satoshi-converter" diff --git a/sdk/src/lib/utils/satoshi-converter.ts b/sdk/src/lib/utils/satoshi-converter.ts new file mode 100644 index 000000000..8178a15d4 --- /dev/null +++ b/sdk/src/lib/utils/satoshi-converter.ts @@ -0,0 +1,15 @@ +/** + * Multiplier to convert satoshi to 1e18 precision. + */ +const SATOSHI_MULTIPLIER = 10n ** 10n + +export function toSatoshi(amount: bigint) { + const remainder = amount % SATOSHI_MULTIPLIER + const satoshis = (amount - remainder) / SATOSHI_MULTIPLIER + + return satoshis +} + +export function fromSatoshi(amount: bigint) { + return amount * SATOSHI_MULTIPLIER +} From 4244f9228a650e5ed35d7112b1e1f91489709bec Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 9 Apr 2024 14:20:49 +0200 Subject: [PATCH 057/110] Add min stake amount to the staking module The minimum amount of BTC deposit should be taken from `BitcoinDepositor` contract. The amount is in tBTC token precision before export this value in SDK has to be converted to satoshi precision. --- sdk/src/lib/contracts/bitcoin-depositor.ts | 5 +++++ sdk/src/lib/ethereum/bitcoin-depositor.ts | 8 ++++++++ sdk/src/modules/staking/index.ts | 9 +++++++++ sdk/test/utils/mock-acre-contracts.ts | 1 + 4 files changed, 23 insertions(+) diff --git a/sdk/src/lib/contracts/bitcoin-depositor.ts b/sdk/src/lib/contracts/bitcoin-depositor.ts index 749f78b73..2786cebec 100644 --- a/sdk/src/lib/contracts/bitcoin-depositor.ts +++ b/sdk/src/lib/contracts/bitcoin-depositor.ts @@ -35,4 +35,9 @@ export interface BitcoinDepositor extends DepositorProxy { * @param extraData Encoded extra data. */ decodeExtraData(extraData: string): DecodedExtraData + + /** + * @returns Minimum stake amount. + */ + minStake(): Promise } diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index d968ee5b6..3677d5ac3 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -128,6 +128,14 @@ class EthereumBitcoinDepositor return { staker, referral } } + + /** + * @see {BitcoinDepositor#minStake} + * @dev The value in tBTC token precision (1e18 precision). + */ + async minStake(): Promise { + return this.instance.minStake() + } } export { EthereumBitcoinDepositor, packRevealDepositParameters } diff --git a/sdk/src/modules/staking/index.ts b/sdk/src/modules/staking/index.ts index 97159b0b2..42a6be2df 100644 --- a/sdk/src/modules/staking/index.ts +++ b/sdk/src/modules/staking/index.ts @@ -2,6 +2,7 @@ import { ChainIdentifier, TBTC } from "@keep-network/tbtc-v2.ts" import { AcreContracts, DepositorProxy } from "../../lib/contracts" import { ChainEIP712Signer } from "../../lib/eip712-signer" import { StakeInitialization } from "./stake-initialization" +import { toSatoshi } from "../../lib/utils" /** * Module exposing features related to the staking. @@ -78,6 +79,14 @@ class StakingModule { estimatedBitcoinBalance(identifier: ChainIdentifier) { return this.#contracts.stBTC.assetsBalanceOf(identifier) } + + /** + * @returns Minimum stake amount in 1e8 satoshi precision. + */ + async minStakeAmount() { + const value = await this.#contracts.bitcoinDepositor.minStake() + return toSatoshi(value) + } } export { StakingModule, StakeInitialization } diff --git a/sdk/test/utils/mock-acre-contracts.ts b/sdk/test/utils/mock-acre-contracts.ts index dfefb5463..82d627cd2 100644 --- a/sdk/test/utils/mock-acre-contracts.ts +++ b/sdk/test/utils/mock-acre-contracts.ts @@ -13,6 +13,7 @@ export class MockAcreContracts implements AcreContracts { decodeExtraData: jest.fn(), encodeExtraData: jest.fn(), revealDeposit: jest.fn(), + minStake: jest.fn(), } as BitcoinDepositor this.stBTC = { From 49b430645219f308f576d32ac5d4986525f0260f Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Tue, 9 Apr 2024 14:26:54 +0200 Subject: [PATCH 058/110] Read the min amount of BTC deposit from the SDK --- dapp/src/hooks/sdk/useFetchMinStakeAmount.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/dapp/src/hooks/sdk/useFetchMinStakeAmount.ts b/dapp/src/hooks/sdk/useFetchMinStakeAmount.ts index 9a2fe7972..6b06b5e03 100644 --- a/dapp/src/hooks/sdk/useFetchMinStakeAmount.ts +++ b/dapp/src/hooks/sdk/useFetchMinStakeAmount.ts @@ -12,10 +12,7 @@ export function useFetchMinStakeAmount() { if (!isInitialized || !acre) return const fetchMinStakeAmount = async () => { - // TODO: Use function from SDK - const minStakeAmount = await new Promise((resolve) => { - resolve(BigInt(String(1e4))) // 0.0001 BTC - }) + const minStakeAmount = await acre.staking.minStakeAmount() dispatch(setMinStakeAmount(minStakeAmount)) } From dc90e68ff7a797649fc935ee5d786173695dcf16 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 10 Apr 2024 09:33:14 +0200 Subject: [PATCH 059/110] Add description for `Toast` component --- dapp/src/components/shared/Toast.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dapp/src/components/shared/Toast.tsx b/dapp/src/components/shared/Toast.tsx index 092163fa7..f341cbe8a 100644 --- a/dapp/src/components/shared/Toast.tsx +++ b/dapp/src/components/shared/Toast.tsx @@ -18,6 +18,9 @@ export default function Toast({ ...props }: ToastProps) { return ( + // Chakra UI uses an alert component for toast under the hood. + // Therefore, to define custom styles for the Toast component, + // need to base it on the Alert component. {title} From 243a507244de167be8e111dc9fb91ef490eea743 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 10 Apr 2024 11:27:18 +0200 Subject: [PATCH 060/110] Add tests for `minStake` from BitcoinDepositor contract --- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 10 ++++++++ sdk/test/modules/staking.test.ts | 27 ++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index 7368af30a..1bbaa59d0 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -18,10 +18,12 @@ describe("BitcoinDepositor", () => { const vaultAddress = EthereumAddress.from( ethers.Wallet.createRandom().address, ) + const minStakeAmount = BigInt(0.015 * 1e18) const mockedContractInstance = { tbtcVault: jest.fn().mockImplementation(() => vaultAddress.identifierHex), initializeStake: jest.fn(), + minStake: jest.fn().mockImplementation(() => minStakeAmount), } let depositor: EthereumBitcoinDepositor let depositorAddress: EthereumAddress @@ -241,4 +243,12 @@ describe("BitcoinDepositor", () => { }, ) }) + + describe("minStake", () => { + it("should return minimum stake amount", async () => { + const result = await depositor.minStake() + + expect(result).toEqual(minStakeAmount) + }) + }) }) diff --git a/sdk/test/modules/staking.test.ts b/sdk/test/modules/staking.test.ts index 6eaca2ead..7e043ea70 100644 --- a/sdk/test/modules/staking.test.ts +++ b/sdk/test/modules/staking.test.ts @@ -12,6 +12,7 @@ import { import { MockAcreContracts } from "../utils/mock-acre-contracts" import { MockMessageSigner } from "../utils/mock-message-signer" import { MockTBTC } from "../utils/mock-tbtc" +import * as satoshiConverterUtils from "../../src/lib/utils/satoshi-converter" const stakingModuleData: { initializeStake: { @@ -395,4 +396,30 @@ describe("Staking", () => { expect(result).toEqual(expectedResult) }) }) + + describe("minStakeAmount", () => { + describe("should return minimum stake amount", () => { + const spyOnToSatoshi = jest.spyOn(satoshiConverterUtils, "toSatoshi") + const mockedResult = BigInt(0.015 * 1e18) + // The returned result should be in satoshi precision + const expectedResult = BigInt(0.015 * 1e8) + let result: bigint + + beforeAll(async () => { + contracts.bitcoinDepositor.minStake = jest + .fn() + .mockResolvedValue(mockedResult) + result = await staking.minStakeAmount() + }) + + it("should convert value to 1e8 satoshi precision", () => { + expect(spyOnToSatoshi).toHaveBeenCalledWith(mockedResult) + expect(spyOnToSatoshi).toHaveReturnedWith(expectedResult) + }) + + it(`should return ${expectedResult}`, () => { + expect(result).toBe(expectedResult) + }) + }) + }) }) From e5c3f3a8dd0fcdb4020f298c7a02e57181c482ab Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 10 Apr 2024 12:03:28 +0200 Subject: [PATCH 061/110] Use bigint type for the token balance in the form Since the minimum staking amount is in bigint, we should standardize it not mix types in the form. This approach also gets rid of the double conversion of tokenBalance to bigint in the `TokenBalanceInput` component and validation method. --- .../ActiveStakingStep/StakeFormModal/index.tsx | 2 +- dapp/src/components/shared/CurrencyBalance/index.tsx | 4 ++-- .../shared/TokenAmountForm/TokenAmountFormBase.tsx | 2 +- dapp/src/components/shared/TokenAmountForm/index.tsx | 2 +- dapp/src/components/shared/TokenBalanceInput/index.tsx | 4 ++-- dapp/src/utils/numbers.ts | 5 +++-- 6 files changed, 10 insertions(+), 9 deletions(-) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx index 70a03a732..1de151fd0 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx @@ -12,7 +12,7 @@ function StakeFormModal({ }) { const minStakeAmount = useMinStakeAmount() const { btcAccount } = useWalletContext() - const tokenBalance = btcAccount?.balance.toString() ?? "0" + const tokenBalance = BigInt(btcAccount?.balance.toString() ?? "0") return ( { const value = amount ?? 0 - if (shouldBeFormatted) + if (shouldBeFormatted || typeof value === "bigint") return formatTokenAmount(value, decimals, desiredDecimals) return numberToLocaleString(value, desiredDecimals) diff --git a/dapp/src/components/shared/TokenAmountForm/TokenAmountFormBase.tsx b/dapp/src/components/shared/TokenAmountForm/TokenAmountFormBase.tsx index 18e4bd712..55a1151f8 100644 --- a/dapp/src/components/shared/TokenAmountForm/TokenAmountFormBase.tsx +++ b/dapp/src/components/shared/TokenAmountForm/TokenAmountFormBase.tsx @@ -19,7 +19,7 @@ export const useTokenAmountFormValue = () => { export type TokenAmountFormBaseProps = { formId?: string - tokenBalance: string + tokenBalance: bigint tokenBalanceInputPlaceholder: string currency: CurrencyType children?: React.ReactNode diff --git a/dapp/src/components/shared/TokenAmountForm/index.tsx b/dapp/src/components/shared/TokenAmountForm/index.tsx index 73d09935c..80850c4e0 100644 --- a/dapp/src/components/shared/TokenAmountForm/index.tsx +++ b/dapp/src/components/shared/TokenAmountForm/index.tsx @@ -20,7 +20,7 @@ const TokenAmountForm = withFormik( errors.amount = validateTokenAmount( amount, - BigInt(tokenBalance), + tokenBalance, minTokenAmount, currency, ) diff --git a/dapp/src/components/shared/TokenBalanceInput/index.tsx b/dapp/src/components/shared/TokenBalanceInput/index.tsx index de55b64dd..e257c48ba 100644 --- a/dapp/src/components/shared/TokenBalanceInput/index.tsx +++ b/dapp/src/components/shared/TokenBalanceInput/index.tsx @@ -87,7 +87,7 @@ function FiatCurrencyBalance({ export type TokenBalanceInputProps = { amount?: bigint currency: CurrencyType - tokenBalance: string | number + tokenBalance: bigint placeholder?: string size?: "lg" | "md" setAmount: (value?: bigint) => void @@ -155,7 +155,7 @@ export default function TokenBalanceInput({ }} /> - diff --git a/dapp/src/utils/numbers.ts b/dapp/src/utils/numbers.ts index 18e629e0c..7f9b63a3d 100644 --- a/dapp/src/utils/numbers.ts +++ b/dapp/src/utils/numbers.ts @@ -48,11 +48,12 @@ export function bigIntToUserAmount( * */ export const formatTokenAmount = ( - amount: number | string, + amount: number | string | bigint, decimals = 18, desiredDecimals = 2, ) => { - const fixedPoint = BigInt(amount) + const isBigInt = typeof amount === "bigint" + const fixedPoint = isBigInt ? amount : BigInt(amount) if (fixedPoint === 0n) { return `0.${"0".repeat(desiredDecimals)}` From 1f55b26dc5ca8700b657f36ab367b28dd8549a03 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 10 Apr 2024 12:17:49 +0200 Subject: [PATCH 062/110] Remove unnecessary conversion to `bigint` --- .../ActiveStakingStep/StakeFormModal/index.tsx | 2 +- dapp/src/components/shared/TokenBalanceInput/index.tsx | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx index 1de151fd0..c6045c90f 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx @@ -25,7 +25,7 @@ function StakeFormModal({ Stake diff --git a/dapp/src/components/shared/TokenBalanceInput/index.tsx b/dapp/src/components/shared/TokenBalanceInput/index.tsx index e257c48ba..f9edbd942 100644 --- a/dapp/src/components/shared/TokenBalanceInput/index.tsx +++ b/dapp/src/components/shared/TokenBalanceInput/index.tsx @@ -143,9 +143,7 @@ export default function TokenBalanceInput({ placeholder={placeholder} {...inputProps} value={ - amount - ? fixedPointNumberToString(BigInt(amount), decimals) - : undefined + amount ? fixedPointNumberToString(amount, decimals) : undefined } onValueChange={(values: NumberFormatInputValues) => handleValueChange(values.value) From d920ad30f4bef7e90b1c30c520dc7c1dc8f305c9 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 10 Apr 2024 12:35:50 +0200 Subject: [PATCH 063/110] Remove unnecessary check condition for bigint The BigInt constructor also accepts the value bigint. There is no need to check whether the number is of type bigint to avoid the constructor. --- dapp/src/utils/numbers.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/dapp/src/utils/numbers.ts b/dapp/src/utils/numbers.ts index 7f9b63a3d..23298e9fe 100644 --- a/dapp/src/utils/numbers.ts +++ b/dapp/src/utils/numbers.ts @@ -52,8 +52,7 @@ export const formatTokenAmount = ( decimals = 18, desiredDecimals = 2, ) => { - const isBigInt = typeof amount === "bigint" - const fixedPoint = isBigInt ? amount : BigInt(amount) + const fixedPoint = BigInt(amount) if (fixedPoint === 0n) { return `0.${"0".repeat(desiredDecimals)}` From 7e0c787245d355e72d886561ac7b5dc2e5fd22f5 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Wed, 10 Apr 2024 12:37:29 +0200 Subject: [PATCH 064/110] Fix issues after merge --- .../ActiveUnstakingStep/UnstakeFormModal/index.tsx | 2 +- dapp/src/hooks/useCurrencyConversion.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx index 19b3cc115..0013e073c 100644 --- a/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx @@ -10,7 +10,7 @@ import { selectMinStakeAmount } from "#/store/btc" import UnstakeDetails from "./UnstakeDetails" // TODO: Use a position amount -const MOCK_POSITION_AMOUNT = "2398567898" +const MOCK_POSITION_AMOUNT = BigInt("2398567898") function UnstakeFormModal({ onSubmitForm, diff --git a/dapp/src/hooks/useCurrencyConversion.ts b/dapp/src/hooks/useCurrencyConversion.ts index f3279c86e..d16925b2e 100644 --- a/dapp/src/hooks/useCurrencyConversion.ts +++ b/dapp/src/hooks/useCurrencyConversion.ts @@ -7,7 +7,7 @@ import { useAppSelector } from "./store" type CurrencyConversionType = { currency: CurrencyType - amount?: number | string + amount?: number | string | bigint } // TODO: should be updated to handle another currencies From 56329fb4db0b9dbc373febcac1cc909b00bd3534 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Thu, 11 Apr 2024 08:41:19 +0200 Subject: [PATCH 065/110] `OverviewPage` component update The previous changes have been restored. Updating the visual layer will be done in a separate task/PR. --- dapp/src/pages/OverviewPage/index.tsx | 42 +++++++++------------------ 1 file changed, 14 insertions(+), 28 deletions(-) diff --git a/dapp/src/pages/OverviewPage/index.tsx b/dapp/src/pages/OverviewPage/index.tsx index 08f283856..2a7433b92 100644 --- a/dapp/src/pages/OverviewPage/index.tsx +++ b/dapp/src/pages/OverviewPage/index.tsx @@ -1,10 +1,8 @@ import React from "react" import { Flex, Grid, HStack, Switch } from "@chakra-ui/react" -import { useDocsDrawer, useWalletContext } from "#/hooks" import { TextSm } from "#/components/shared/Typography" import { USD } from "#/constants" import { chakraUnitToPx } from "#/theme/utils" -import ButtonLink from "#/components/shared/ButtonLink" import PositionDetails from "./PositionDetails" import Statistics from "./Statistics" import TransactionHistory from "./TransactionHistory" @@ -12,33 +10,21 @@ import { DocsCard } from "./DocsCard" import { ActivityCarousel } from "./ActivityCarousel" export default function OverviewPage() { - const { onOpen } = useDocsDrawer() - const { isConnected } = useWalletContext() - return ( - - - - {/* TODO: Handle click actions */} - - Show values in {USD.symbol} - - {!isConnected && ( - - Docs - - )} - - {/* TODO: Add animation to show activity bar */} - {isConnected && ( - - - - - )} + + + {/* TODO: Handle click actions */} + + Show values in {USD.symbol} + + + + + + Date: Thu, 11 Apr 2024 17:34:30 +0200 Subject: [PATCH 066/110] Add deployment artifacts for sepolia We redeployed the latest version of contracts to sepolia. --- solidity/.openzeppelin/sepolia.json | 888 ++++++++++++++++ .../deployments/sepolia/BitcoinDepositor.json | 911 +++-------------- .../deployments/sepolia/BitcoinRedeemer.json | 354 +++++++ .../deployments/sepolia/MezoAllocator.json | 513 ++++++++++ .../49f0432287e96a47d66ba17ae7bf5d96.json | 117 --- .../b22c277b248ba02f9ec5bf62d176f9ce.json | 114 --- solidity/deployments/sepolia/stBTC.json | 951 ++++++------------ 7 files changed, 2169 insertions(+), 1679 deletions(-) create mode 100644 solidity/.openzeppelin/sepolia.json create mode 100644 solidity/deployments/sepolia/BitcoinRedeemer.json create mode 100644 solidity/deployments/sepolia/MezoAllocator.json delete mode 100644 solidity/deployments/sepolia/solcInputs/49f0432287e96a47d66ba17ae7bf5d96.json delete mode 100644 solidity/deployments/sepolia/solcInputs/b22c277b248ba02f9ec5bf62d176f9ce.json diff --git a/solidity/.openzeppelin/sepolia.json b/solidity/.openzeppelin/sepolia.json new file mode 100644 index 000000000..59a3b3409 --- /dev/null +++ b/solidity/.openzeppelin/sepolia.json @@ -0,0 +1,888 @@ +{ + "manifestVersion": "3.2", + "proxies": [ + { + "address": "0xc14972DC5a4443E4f5e89E3655BE48Ee95A795aB", + "txHash": "0x86123a76a3d2e04e1d1d925635a72165d75e10b245cf9a0c67ea7edb05514bad", + "kind": "transparent" + }, + { + "address": "0x43D17826b31E03c11b46427B68613422A3621b6f", + "txHash": "0xfb55581567b9c25430937117bb3e1f52bae0f4431d90c0984d1998cac74b1f73", + "kind": "transparent" + }, + { + "address": "0x2F86FE8C5683372Db667E6f6d88dcB6d55a81286", + "txHash": "0xf48fcfd4e3bed67f73675366c46427b9a19c29a25ea3a4432bbb48df240a6785", + "kind": "transparent" + }, + { + "address": "0x0E781e9D538895EE99bd6e9Bf28664942beFF32f", + "txHash": "0xa7da2f83d258beac8b9f05d14ff2452842c535d8624f91ae31b4a4857ad1eecf", + "kind": "transparent" + } + ], + "impls": { + "b48ad0fa2722ed27bc88a392a20fe46c5b407a4c393fe4e2fd1a79e6f7035c5f": { + "address": "0x5e6A8368005AD055590AB8C7f9DB6f9f6860f634", + "txHash": "0x7487b45b302647f6baad30106f8a2509e642e5590de1b0553ab221446b207373", + "layout": { + "solcVersion": "0.8.21", + "storage": [ + { + "label": "pauseAdmin", + "offset": 0, + "slot": "0", + "type": "t_address", + "contract": "PausableOwnable", + "src": "contracts/PausableOwnable.sol:19" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)49_storage", + "contract": "PausableOwnable", + "src": "contracts/PausableOwnable.sol:27" + }, + { + "label": "dispatcher", + "offset": 0, + "slot": "50", + "type": "t_contract(IDispatcher)11687", + "contract": "stBTC", + "src": "contracts/stBTC.sol:29" + }, + { + "label": "treasury", + "offset": 0, + "slot": "51", + "type": "t_address", + "contract": "stBTC", + "src": "contracts/stBTC.sol:32" + }, + { + "label": "minimumDepositAmount", + "offset": 0, + "slot": "52", + "type": "t_uint256", + "contract": "stBTC", + "src": "contracts/stBTC.sol:39" + }, + { + "label": "entryFeeBasisPoints", + "offset": 0, + "slot": "53", + "type": "t_uint256", + "contract": "stBTC", + "src": "contracts/stBTC.sol:42" + }, + { + "label": "exitFeeBasisPoints", + "offset": 0, + "slot": "54", + "type": "t_uint256", + "contract": "stBTC", + "src": "contracts/stBTC.sol:45" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_contract(IERC20)1137": { + "label": "contract IERC20", + "numberOfBytes": "20" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_uint256)": { + "label": "mapping(address => uint256)", + "numberOfBytes": "32" + }, + "t_string_storage": { + "label": "string", + "numberOfBytes": "32" + }, + "t_struct(ERC20Storage)628_storage": { + "label": "struct ERC20Upgradeable.ERC20Storage", + "members": [ + { + "label": "_balances", + "type": "t_mapping(t_address,t_uint256)", + "offset": 0, + "slot": "0" + }, + { + "label": "_allowances", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", + "offset": 0, + "slot": "1" + }, + { + "label": "_totalSupply", + "type": "t_uint256", + "offset": 0, + "slot": "2" + }, + { + "label": "_name", + "type": "t_string_storage", + "offset": 0, + "slot": "3" + }, + { + "label": "_symbol", + "type": "t_string_storage", + "offset": 0, + "slot": "4" + } + ], + "numberOfBytes": "160" + }, + "t_struct(ERC4626Storage)721_storage": { + "label": "struct ERC4626Upgradeable.ERC4626Storage", + "members": [ + { + "label": "_asset", + "type": "t_contract(IERC20)1137", + "offset": 0, + "slot": "0" + }, + { + "label": "_underlyingDecimals", + "type": "t_uint8", + "offset": 20, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_struct(InitializableStorage)548_storage": { + "label": "struct Initializable.InitializableStorage", + "members": [ + { + "label": "_initialized", + "type": "t_uint64", + "offset": 0, + "slot": "0" + }, + { + "label": "_initializing", + "type": "t_bool", + "offset": 8, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_struct(Ownable2StepStorage)457_storage": { + "label": "struct Ownable2StepUpgradeable.Ownable2StepStorage", + "members": [ + { + "label": "_pendingOwner", + "type": "t_address", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_struct(OwnableStorage)498_storage": { + "label": "struct OwnableUpgradeable.OwnableStorage", + "members": [ + { + "label": "_owner", + "type": "t_address", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_struct(PausableStorage)847_storage": { + "label": "struct PausableUpgradeable.PausableStorage", + "members": [ + { + "label": "_paused", + "type": "t_bool", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint64": { + "label": "uint64", + "numberOfBytes": "8" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + }, + "t_array(t_uint256)49_storage": { + "label": "uint256[49]", + "numberOfBytes": "1568" + }, + "t_contract(IDispatcher)11687": { + "label": "contract IDispatcher", + "numberOfBytes": "20" + } + }, + "namespaces": { + "erc7201:openzeppelin.storage.Ownable2Step": [ + { + "contract": "Ownable2StepUpgradeable", + "label": "_pendingOwner", + "type": "t_address", + "src": "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol:23", + "offset": 0, + "slot": "0" + } + ], + "erc7201:openzeppelin.storage.Ownable": [ + { + "contract": "OwnableUpgradeable", + "label": "_owner", + "type": "t_address", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:24", + "offset": 0, + "slot": "0" + } + ], + "erc7201:openzeppelin.storage.Pausable": [ + { + "contract": "PausableUpgradeable", + "label": "_paused", + "type": "t_bool", + "src": "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol:21", + "offset": 0, + "slot": "0" + } + ], + "erc7201:openzeppelin.storage.ERC4626": [ + { + "contract": "ERC4626Upgradeable", + "label": "_asset", + "type": "t_contract(IERC20)1137", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol:56", + "offset": 0, + "slot": "0" + }, + { + "contract": "ERC4626Upgradeable", + "label": "_underlyingDecimals", + "type": "t_uint8", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol:57", + "offset": 20, + "slot": "0" + } + ], + "erc7201:openzeppelin.storage.ERC20": [ + { + "contract": "ERC20Upgradeable", + "label": "_balances", + "type": "t_mapping(t_address,t_uint256)", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:38", + "offset": 0, + "slot": "0" + }, + { + "contract": "ERC20Upgradeable", + "label": "_allowances", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:40", + "offset": 0, + "slot": "1" + }, + { + "contract": "ERC20Upgradeable", + "label": "_totalSupply", + "type": "t_uint256", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:42", + "offset": 0, + "slot": "2" + }, + { + "contract": "ERC20Upgradeable", + "label": "_name", + "type": "t_string_storage", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:44", + "offset": 0, + "slot": "3" + }, + { + "contract": "ERC20Upgradeable", + "label": "_symbol", + "type": "t_string_storage", + "src": "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol:45", + "offset": 0, + "slot": "4" + } + ], + "erc7201:openzeppelin.storage.Initializable": [ + { + "contract": "Initializable", + "label": "_initialized", + "type": "t_uint64", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:69", + "offset": 0, + "slot": "0" + }, + { + "contract": "Initializable", + "label": "_initializing", + "type": "t_bool", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:73", + "offset": 8, + "slot": "0" + } + ] + } + } + }, + "e8516732d43f130f2fe9d55ff46c8ba066800935bf3f2b5fd44e240b7f693e92": { + "address": "0x09F851AD4e927755453E253557A5383B67925a35", + "txHash": "0x9bcff8bd07643ea0a21793df5ad0c4d5d3c9a30f7fd83d68ea62e06486136a16", + "layout": { + "solcVersion": "0.8.21", + "storage": [ + { + "label": "mezoPortal", + "offset": 0, + "slot": "0", + "type": "t_contract(IMezoPortal)10988", + "contract": "MezoAllocator", + "src": "contracts/MezoAllocator.sol:66" + }, + { + "label": "tbtc", + "offset": 0, + "slot": "1", + "type": "t_contract(IERC20)6702", + "contract": "MezoAllocator", + "src": "contracts/MezoAllocator.sol:68" + }, + { + "label": "stbtc", + "offset": 0, + "slot": "2", + "type": "t_contract(stBTC)12563", + "contract": "MezoAllocator", + "src": "contracts/MezoAllocator.sol:70" + }, + { + "label": "isMaintainer", + "offset": 0, + "slot": "3", + "type": "t_mapping(t_address,t_bool)", + "contract": "MezoAllocator", + "src": "contracts/MezoAllocator.sol:73" + }, + { + "label": "maintainers", + "offset": 0, + "slot": "4", + "type": "t_array(t_address)dyn_storage", + "contract": "MezoAllocator", + "src": "contracts/MezoAllocator.sol:75" + }, + { + "label": "depositId", + "offset": 0, + "slot": "5", + "type": "t_uint256", + "contract": "MezoAllocator", + "src": "contracts/MezoAllocator.sol:77" + }, + { + "label": "depositBalance", + "offset": 0, + "slot": "6", + "type": "t_uint96", + "contract": "MezoAllocator", + "src": "contracts/MezoAllocator.sol:79" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_struct(InitializableStorage)548_storage": { + "label": "struct Initializable.InitializableStorage", + "members": [ + { + "label": "_initialized", + "type": "t_uint64", + "offset": 0, + "slot": "0" + }, + { + "label": "_initializing", + "type": "t_bool", + "offset": 8, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_struct(Ownable2StepStorage)457_storage": { + "label": "struct Ownable2StepUpgradeable.Ownable2StepStorage", + "members": [ + { + "label": "_pendingOwner", + "type": "t_address", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_struct(OwnableStorage)498_storage": { + "label": "struct OwnableUpgradeable.OwnableStorage", + "members": [ + { + "label": "_owner", + "type": "t_address", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_uint64": { + "label": "uint64", + "numberOfBytes": "8" + }, + "t_array(t_address)dyn_storage": { + "label": "address[]", + "numberOfBytes": "32" + }, + "t_contract(IERC20)6702": { + "label": "contract IERC20", + "numberOfBytes": "20" + }, + "t_contract(IMezoPortal)10988": { + "label": "contract IMezoPortal", + "numberOfBytes": "20" + }, + "t_contract(stBTC)12563": { + "label": "contract stBTC", + "numberOfBytes": "20" + }, + "t_mapping(t_address,t_bool)": { + "label": "mapping(address => bool)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint96": { + "label": "uint96", + "numberOfBytes": "12" + } + }, + "namespaces": { + "erc7201:openzeppelin.storage.Ownable2Step": [ + { + "contract": "Ownable2StepUpgradeable", + "label": "_pendingOwner", + "type": "t_address", + "src": "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol:23", + "offset": 0, + "slot": "0" + } + ], + "erc7201:openzeppelin.storage.Ownable": [ + { + "contract": "OwnableUpgradeable", + "label": "_owner", + "type": "t_address", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:24", + "offset": 0, + "slot": "0" + } + ], + "erc7201:openzeppelin.storage.Initializable": [ + { + "contract": "Initializable", + "label": "_initialized", + "type": "t_uint64", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:69", + "offset": 0, + "slot": "0" + }, + { + "contract": "Initializable", + "label": "_initializing", + "type": "t_bool", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:73", + "offset": 8, + "slot": "0" + } + ] + } + } + }, + "052b0b9d87cc9bd42e4b36e11b005f5bacbf2f82ca1657b3e5c5eb7951e09ecc": { + "address": "0x859aB3c72642d07c3c389817624a9D8da06BBF71", + "txHash": "0xe0a1fef2bcf3559d18868dde62ab0da3abd61f68766dd5db1361ef621b9b506b", + "layout": { + "solcVersion": "0.8.21", + "storage": [ + { + "label": "bridge", + "offset": 0, + "slot": "0", + "type": "t_contract(IBridge)3081", + "contract": "AbstractTBTCDepositor", + "src": "@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol:95" + }, + { + "label": "tbtcVault", + "offset": 0, + "slot": "1", + "type": "t_contract(ITBTCVault)3107", + "contract": "AbstractTBTCDepositor", + "src": "@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol:96" + }, + { + "label": "__gap", + "offset": 0, + "slot": "2", + "type": "t_array(t_uint256)47_storage", + "contract": "AbstractTBTCDepositor", + "src": "@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol:111" + }, + { + "label": "deposits", + "offset": 0, + "slot": "49", + "type": "t_mapping(t_uint256,t_enum(DepositState)10182)", + "contract": "BitcoinDepositor", + "src": "contracts/BitcoinDepositor.sol:57" + }, + { + "label": "tbtcToken", + "offset": 0, + "slot": "50", + "type": "t_contract(IERC20)6702", + "contract": "BitcoinDepositor", + "src": "contracts/BitcoinDepositor.sol:60" + }, + { + "label": "stbtc", + "offset": 0, + "slot": "51", + "type": "t_contract(stBTC)12563", + "contract": "BitcoinDepositor", + "src": "contracts/BitcoinDepositor.sol:63" + }, + { + "label": "minDepositAmount", + "offset": 0, + "slot": "52", + "type": "t_uint256", + "contract": "BitcoinDepositor", + "src": "contracts/BitcoinDepositor.sol:68" + }, + { + "label": "depositorFeeDivisor", + "offset": 0, + "slot": "53", + "type": "t_uint64", + "contract": "BitcoinDepositor", + "src": "contracts/BitcoinDepositor.sol:77" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_struct(InitializableStorage)548_storage": { + "label": "struct Initializable.InitializableStorage", + "members": [ + { + "label": "_initialized", + "type": "t_uint64", + "offset": 0, + "slot": "0" + }, + { + "label": "_initializing", + "type": "t_bool", + "offset": 8, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_struct(Ownable2StepStorage)457_storage": { + "label": "struct Ownable2StepUpgradeable.Ownable2StepStorage", + "members": [ + { + "label": "_pendingOwner", + "type": "t_address", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_struct(OwnableStorage)498_storage": { + "label": "struct OwnableUpgradeable.OwnableStorage", + "members": [ + { + "label": "_owner", + "type": "t_address", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_uint64": { + "label": "uint64", + "numberOfBytes": "8" + }, + "t_array(t_uint256)47_storage": { + "label": "uint256[47]", + "numberOfBytes": "1504" + }, + "t_contract(IBridge)3081": { + "label": "contract IBridge", + "numberOfBytes": "20" + }, + "t_contract(IERC20)6702": { + "label": "contract IERC20", + "numberOfBytes": "20" + }, + "t_contract(ITBTCVault)3107": { + "label": "contract ITBTCVault", + "numberOfBytes": "20" + }, + "t_contract(stBTC)12563": { + "label": "contract stBTC", + "numberOfBytes": "20" + }, + "t_enum(DepositState)10182": { + "label": "enum BitcoinDepositor.DepositState", + "members": [ + "Unknown", + "Initialized", + "Finalized" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_uint256,t_enum(DepositState)10182)": { + "label": "mapping(uint256 => enum BitcoinDepositor.DepositState)", + "numberOfBytes": "32" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + } + }, + "namespaces": { + "erc7201:openzeppelin.storage.Ownable2Step": [ + { + "contract": "Ownable2StepUpgradeable", + "label": "_pendingOwner", + "type": "t_address", + "src": "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol:23", + "offset": 0, + "slot": "0" + } + ], + "erc7201:openzeppelin.storage.Ownable": [ + { + "contract": "OwnableUpgradeable", + "label": "_owner", + "type": "t_address", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:24", + "offset": 0, + "slot": "0" + } + ], + "erc7201:openzeppelin.storage.Initializable": [ + { + "contract": "Initializable", + "label": "_initialized", + "type": "t_uint64", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:69", + "offset": 0, + "slot": "0" + }, + { + "contract": "Initializable", + "label": "_initializing", + "type": "t_bool", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:73", + "offset": 8, + "slot": "0" + } + ] + } + } + }, + "5b478310bffc787541df401b8522361ad860f22132bd9f3f06eca11833dbd36d": { + "address": "0x88B0Aa9BAfB9573871683b49407cD7d99668C786", + "txHash": "0x2553503830d1064c1c3aa320aca650aa4221a08f66c740e1b0ae7a4f693bca58", + "layout": { + "solcVersion": "0.8.21", + "storage": [ + { + "label": "tbtcToken", + "offset": 0, + "slot": "0", + "type": "t_contract(ITBTCToken)11671", + "contract": "BitcoinRedeemer", + "src": "contracts/BitcoinRedeemer.sol:17" + }, + { + "label": "stbtc", + "offset": 0, + "slot": "1", + "type": "t_contract(stBTC)12563", + "contract": "BitcoinRedeemer", + "src": "contracts/BitcoinRedeemer.sol:20" + }, + { + "label": "tbtcVault", + "offset": 0, + "slot": "2", + "type": "t_address", + "contract": "BitcoinRedeemer", + "src": "contracts/BitcoinRedeemer.sol:23" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_struct(InitializableStorage)548_storage": { + "label": "struct Initializable.InitializableStorage", + "members": [ + { + "label": "_initialized", + "type": "t_uint64", + "offset": 0, + "slot": "0" + }, + { + "label": "_initializing", + "type": "t_bool", + "offset": 8, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_struct(Ownable2StepStorage)457_storage": { + "label": "struct Ownable2StepUpgradeable.Ownable2StepStorage", + "members": [ + { + "label": "_pendingOwner", + "type": "t_address", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_struct(OwnableStorage)498_storage": { + "label": "struct OwnableUpgradeable.OwnableStorage", + "members": [ + { + "label": "_owner", + "type": "t_address", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "32" + }, + "t_uint64": { + "label": "uint64", + "numberOfBytes": "8" + }, + "t_contract(ITBTCToken)11671": { + "label": "contract ITBTCToken", + "numberOfBytes": "20" + }, + "t_contract(stBTC)12563": { + "label": "contract stBTC", + "numberOfBytes": "20" + } + }, + "namespaces": { + "erc7201:openzeppelin.storage.Ownable2Step": [ + { + "contract": "Ownable2StepUpgradeable", + "label": "_pendingOwner", + "type": "t_address", + "src": "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol:23", + "offset": 0, + "slot": "0" + } + ], + "erc7201:openzeppelin.storage.Ownable": [ + { + "contract": "OwnableUpgradeable", + "label": "_owner", + "type": "t_address", + "src": "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol:24", + "offset": 0, + "slot": "0" + } + ], + "erc7201:openzeppelin.storage.Initializable": [ + { + "contract": "Initializable", + "label": "_initialized", + "type": "t_uint64", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:69", + "offset": 0, + "slot": "0" + }, + { + "contract": "Initializable", + "label": "_initializing", + "type": "t_bool", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:73", + "offset": 8, + "slot": "0" + } + ] + } + } + } + } +} diff --git a/solidity/deployments/sepolia/BitcoinDepositor.json b/solidity/deployments/sepolia/BitcoinDepositor.json index c09f41dfd..127f98cba 100644 --- a/solidity/deployments/sepolia/BitcoinDepositor.json +++ b/solidity/deployments/sepolia/BitcoinDepositor.json @@ -1,29 +1,8 @@ { - "address": "0x37E34EbC743FFAf96b56b3f62854bb7E733a4B50", + "address": "0x2F86FE8C5683372Db667E6f6d88dcB6d55a81286", "abi": [ { - "inputs": [ - { - "internalType": "address", - "name": "bridge", - "type": "address" - }, - { - "internalType": "address", - "name": "tbtcVault", - "type": "address" - }, - { - "internalType": "address", - "name": "_tbtcToken", - "type": "address" - }, - { - "internalType": "address", - "name": "_stbtc", - "type": "address" - } - ], + "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, @@ -51,22 +30,7 @@ }, { "inputs": [], - "name": "BridgingCompletionAlreadyNotified", - "type": "error" - }, - { - "inputs": [], - "name": "BridgingFinalizationAlreadyCalled", - "type": "error" - }, - { - "inputs": [], - "name": "BridgingNotCompleted", - "type": "error" - }, - { - "inputs": [], - "name": "CallerNotStaker", + "name": "DepositOwnerIsZeroAddress", "type": "error" }, { @@ -90,20 +54,30 @@ "name": "FailedInnerCall", "type": "error" }, + { + "inputs": [], + "name": "InvalidInitialization", + "type": "error" + }, { "inputs": [ { "internalType": "uint256", - "name": "amountToStake", + "name": "minDepositAmount", "type": "uint256" }, { "internalType": "uint256", - "name": "currentBalance", + "name": "bridgeMinDepositAmount", "type": "uint256" } ], - "name": "InsufficientTbtcBalance", + "name": "MinDepositAmountLowerThanBridgeMinDeposit", + "type": "error" + }, + { + "inputs": [], + "name": "NotInitializing", "type": "error" }, { @@ -128,22 +102,6 @@ "name": "OwnableUnauthorizedAccount", "type": "error" }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "bits", - "type": "uint8" - }, - { - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "SafeCastOverflowedUintDowncast", - "type": "error" - }, { "inputs": [ { @@ -155,16 +113,6 @@ "name": "SafeERC20FailedOperation", "type": "error" }, - { - "inputs": [], - "name": "StakeRequestNotQueued", - "type": "error" - }, - { - "inputs": [], - "name": "StakerIsZeroAddress", - "type": "error" - }, { "inputs": [], "name": "StbtcZeroAddress", @@ -178,17 +126,17 @@ { "inputs": [ { - "internalType": "enum AcreBitcoinDepositor.StakeRequestState", - "name": "currentState", + "internalType": "enum BitcoinDepositor.DepositState", + "name": "actualState", "type": "uint8" }, { - "internalType": "enum AcreBitcoinDepositor.StakeRequestState", + "internalType": "enum BitcoinDepositor.DepositState", "name": "expectedState", "type": "uint8" } ], - "name": "UnexpectedStakeRequestState", + "name": "UnexpectedDepositState", "type": "error" }, { @@ -215,39 +163,20 @@ { "indexed": false, "internalType": "uint256", - "name": "bridgedAmount", + "name": "initialAmount", "type": "uint256" }, { "indexed": false, "internalType": "uint256", - "name": "depositorFee", - "type": "uint256" - } - ], - "name": "BridgingCompleted", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", + "name": "bridgedAmount", "type": "uint256" }, { "indexed": false, "internalType": "uint256", - "name": "tbtcAmount", + "name": "depositorFee", "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint32", - "name": "finalizedAt", - "type": "uint32" } ], "name": "DepositFinalized", @@ -262,165 +191,84 @@ "name": "depositKey", "type": "uint256" }, - { - "indexed": false, - "internalType": "uint32", - "name": "initializedAt", - "type": "uint32" - } - ], - "name": "DepositInitialized", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint64", - "name": "depositorFeeDivisor", - "type": "uint64" - } - ], - "name": "DepositorFeeDivisorUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ { "indexed": true, "internalType": "address", - "name": "previousOwner", + "name": "caller", "type": "address" }, { "indexed": true, "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "OwnershipTransferStarted", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "previousOwner", + "name": "depositOwner", "type": "address" }, { - "indexed": true, - "internalType": "address", - "name": "newOwner", - "type": "address" + "indexed": false, + "internalType": "uint256", + "name": "initialAmount", + "type": "uint256" } ], - "name": "OwnershipTransferred", + "name": "DepositInitialized", "type": "event" }, { "anonymous": false, "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, - { - "indexed": true, - "internalType": "address", - "name": "staker", - "type": "address" - }, { "indexed": false, - "internalType": "uint256", - "name": "amountToStake", - "type": "uint256" + "internalType": "uint64", + "name": "depositorFeeDivisor", + "type": "uint64" } ], - "name": "StakeRequestCancelledFromQueue", + "name": "DepositorFeeDivisorUpdated", "type": "event" }, { "anonymous": false, "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, - { - "indexed": true, - "internalType": "address", - "name": "caller", - "type": "address" - }, { "indexed": false, - "internalType": "uint256", - "name": "stakedAmount", - "type": "uint256" + "internalType": "uint64", + "name": "version", + "type": "uint64" } ], - "name": "StakeRequestFinalized", + "name": "Initialized", "type": "event" }, { "anonymous": false, "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, - { - "indexed": true, - "internalType": "address", - "name": "caller", - "type": "address" - }, { "indexed": false, "internalType": "uint256", - "name": "stakedAmount", + "name": "minDepositAmount", "type": "uint256" } ], - "name": "StakeRequestFinalizedFromQueue", + "name": "MinDepositAmountUpdated", "type": "event" }, { "anonymous": false, "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, { "indexed": true, "internalType": "address", - "name": "caller", + "name": "previousOwner", "type": "address" }, { "indexed": true, "internalType": "address", - "name": "staker", + "name": "newOwner", "type": "address" } ], - "name": "StakeRequestInitialized", + "name": "OwnershipTransferStarted", "type": "event" }, { @@ -428,24 +276,18 @@ "inputs": [ { "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" + "internalType": "address", + "name": "previousOwner", + "type": "address" }, { "indexed": true, "internalType": "address", - "name": "caller", + "name": "newOwner", "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "queuedAmount", - "type": "uint256" } ], - "name": "StakeRequestQueued", + "name": "OwnershipTransferred", "type": "event" }, { @@ -481,19 +323,6 @@ "stateMutability": "view", "type": "function" }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - } - ], - "name": "cancelQueuedStake", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, { "inputs": [ { @@ -506,7 +335,7 @@ "outputs": [ { "internalType": "address", - "name": "staker", + "name": "depositOwner", "type": "address" }, { @@ -531,11 +360,30 @@ "stateMutability": "view", "type": "function" }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "name": "deposits", + "outputs": [ + { + "internalType": "enum BitcoinDepositor.DepositState", + "name": "", + "type": "uint8" + } + ], + "stateMutability": "view", + "type": "function" + }, { "inputs": [ { "internalType": "address", - "name": "staker", + "name": "depositOwner", "type": "address" }, { @@ -563,7 +411,7 @@ "type": "uint256" } ], - "name": "finalizeQueuedStake", + "name": "finalizeDeposit", "outputs": [], "stateMutability": "nonpayable", "type": "function" @@ -571,12 +419,27 @@ { "inputs": [ { - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" + "internalType": "address", + "name": "bridge", + "type": "address" + }, + { + "internalType": "address", + "name": "tbtcVault", + "type": "address" + }, + { + "internalType": "address", + "name": "_tbtcToken", + "type": "address" + }, + { + "internalType": "address", + "name": "_stbtc", + "type": "address" } ], - "name": "finalizeStake", + "name": "initialize", "outputs": [], "stateMutability": "nonpayable", "type": "function" @@ -649,7 +512,7 @@ }, { "internalType": "address", - "name": "staker", + "name": "depositOwner", "type": "address" }, { @@ -658,19 +521,19 @@ "type": "uint16" } ], - "name": "initializeStake", + "name": "initializeDeposit", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], - "name": "owner", + "name": "minDepositAmount", "outputs": [ { - "internalType": "address", + "internalType": "uint256", "name": "", - "type": "address" + "type": "uint256" } ], "stateMutability": "view", @@ -678,7 +541,7 @@ }, { "inputs": [], - "name": "pendingOwner", + "name": "owner", "outputs": [ { "internalType": "address", @@ -690,16 +553,16 @@ "type": "function" }, { - "inputs": [ + "inputs": [], + "name": "pendingOwner", + "outputs": [ { - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" + "internalType": "address", + "name": "", + "type": "address" } ], - "name": "queueStake", - "outputs": [], - "stateMutability": "nonpayable", + "stateMutability": "view", "type": "function" }, { @@ -709,35 +572,6 @@ "stateMutability": "nonpayable", "type": "function" }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "name": "stakeRequests", - "outputs": [ - { - "internalType": "enum AcreBitcoinDepositor.StakeRequestState", - "name": "state", - "type": "uint8" - }, - { - "internalType": "address", - "name": "staker", - "type": "address" - }, - { - "internalType": "uint88", - "name": "queuedAmount", - "type": "uint88" - } - ], - "stateMutability": "view", - "type": "function" - }, { "inputs": [], "name": "stbtc", @@ -802,536 +636,23 @@ "outputs": [], "stateMutability": "nonpayable", "type": "function" - } - ], - "transactionHash": "0x6f7d1a83200314126aa36f4aaac2450d2a0c1ffd77a53327d35bf6c0331d4bec", - "receipt": { - "to": null, - "from": "0x2d154A5c7cE9939274b89bbCe9f5B069E57b09A8", - "contractAddress": "0x37E34EbC743FFAf96b56b3f62854bb7E733a4B50", - "transactionIndex": 157, - "gasUsed": "2013605", - "logsBloom": "0x00000000000000000000000000000000000000000000000000800000000000000002000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000001000000000000000000000000000000400000020000000000000000000800000000000000000000000000000000400000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000012000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0x13e2258b7e01b5bb7b0c5d438c0e623c89056660447e4bff2cd8a812392a6df5", - "transactionHash": "0x6f7d1a83200314126aa36f4aaac2450d2a0c1ffd77a53327d35bf6c0331d4bec", - "logs": [ - { - "transactionIndex": 157, - "blockNumber": 5387080, - "transactionHash": "0x6f7d1a83200314126aa36f4aaac2450d2a0c1ffd77a53327d35bf6c0331d4bec", - "address": "0x37E34EbC743FFAf96b56b3f62854bb7E733a4B50", - "topics": [ - "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", - "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x0000000000000000000000002d154a5c7ce9939274b89bbce9f5b069e57b09a8" - ], - "data": "0x", - "logIndex": 237, - "blockHash": "0x13e2258b7e01b5bb7b0c5d438c0e623c89056660447e4bff2cd8a812392a6df5" - } - ], - "blockNumber": 5387080, - "cumulativeGasUsed": "27025873", - "status": 1, - "byzantium": true - }, - "args": [ - "0x9b1a7fE5a16A15F2f9475C5B231750598b113403", - "0xB5679dE944A79732A75CE556191DF11F489448d5", - "0x517f2982701695D4E52f1ECFBEf3ba31Df470161", - "0xF99139f09164B092bD9e8558984Becfb0d2eCb87" - ], - "numDeployments": 1, - "solcInputHash": "49f0432287e96a47d66ba17ae7bf5d96", - "metadata": "{\"compiler\":{\"version\":\"0.8.21+commit.d9974bed\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"bridge\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tbtcVault\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_tbtcToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_stbtc\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"}],\"name\":\"AddressEmptyCode\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"AddressInsufficientBalance\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"BridgingCompletionAlreadyNotified\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"BridgingFinalizationAlreadyCalled\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"BridgingNotCompleted\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"CallerNotStaker\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"depositorFee\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"bridgedAmount\",\"type\":\"uint256\"}],\"name\":\"DepositorFeeExceedsBridgedAmount\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"FailedInnerCall\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountToStake\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"currentBalance\",\"type\":\"uint256\"}],\"name\":\"InsufficientTbtcBalance\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"OwnableInvalidOwner\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"OwnableUnauthorizedAccount\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint8\",\"name\":\"bits\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"SafeCastOverflowedUintDowncast\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"SafeERC20FailedOperation\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"StakeRequestNotQueued\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"StakerIsZeroAddress\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"StbtcZeroAddress\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"TbtcTokenZeroAddress\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"enum AcreBitcoinDepositor.StakeRequestState\",\"name\":\"currentState\",\"type\":\"uint8\"},{\"internalType\":\"enum AcreBitcoinDepositor.StakeRequestState\",\"name\":\"expectedState\",\"type\":\"uint8\"}],\"name\":\"UnexpectedStakeRequestState\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint16\",\"name\":\"referral\",\"type\":\"uint16\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"bridgedAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"depositorFee\",\"type\":\"uint256\"}],\"name\":\"BridgingCompleted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"tbtcAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"finalizedAt\",\"type\":\"uint32\"}],\"name\":\"DepositFinalized\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"initializedAt\",\"type\":\"uint32\"}],\"name\":\"DepositInitialized\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint64\",\"name\":\"depositorFeeDivisor\",\"type\":\"uint64\"}],\"name\":\"DepositorFeeDivisorUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferStarted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amountToStake\",\"type\":\"uint256\"}],\"name\":\"StakeRequestCancelledFromQueue\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"stakedAmount\",\"type\":\"uint256\"}],\"name\":\"StakeRequestFinalized\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"stakedAmount\",\"type\":\"uint256\"}],\"name\":\"StakeRequestFinalizedFromQueue\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"}],\"name\":\"StakeRequestInitialized\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"queuedAmount\",\"type\":\"uint256\"}],\"name\":\"StakeRequestQueued\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"SATOSHI_MULTIPLIER\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"acceptOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"bridge\",\"outputs\":[{\"internalType\":\"contract IBridge\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"}],\"name\":\"cancelQueuedStake\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"extraData\",\"type\":\"bytes32\"}],\"name\":\"decodeExtraData\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"},{\"internalType\":\"uint16\",\"name\":\"referral\",\"type\":\"uint16\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"depositorFeeDivisor\",\"outputs\":[{\"internalType\":\"uint64\",\"name\":\"\",\"type\":\"uint64\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"},{\"internalType\":\"uint16\",\"name\":\"referral\",\"type\":\"uint16\"}],\"name\":\"encodeExtraData\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"}],\"name\":\"finalizeQueuedStake\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"}],\"name\":\"finalizeStake\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"bytes4\",\"name\":\"version\",\"type\":\"bytes4\"},{\"internalType\":\"bytes\",\"name\":\"inputVector\",\"type\":\"bytes\"},{\"internalType\":\"bytes\",\"name\":\"outputVector\",\"type\":\"bytes\"},{\"internalType\":\"bytes4\",\"name\":\"locktime\",\"type\":\"bytes4\"}],\"internalType\":\"struct IBridgeTypes.BitcoinTxInfo\",\"name\":\"fundingTx\",\"type\":\"tuple\"},{\"components\":[{\"internalType\":\"uint32\",\"name\":\"fundingOutputIndex\",\"type\":\"uint32\"},{\"internalType\":\"bytes8\",\"name\":\"blindingFactor\",\"type\":\"bytes8\"},{\"internalType\":\"bytes20\",\"name\":\"walletPubKeyHash\",\"type\":\"bytes20\"},{\"internalType\":\"bytes20\",\"name\":\"refundPubKeyHash\",\"type\":\"bytes20\"},{\"internalType\":\"bytes4\",\"name\":\"refundLocktime\",\"type\":\"bytes4\"},{\"internalType\":\"address\",\"name\":\"vault\",\"type\":\"address\"}],\"internalType\":\"struct IBridgeTypes.DepositRevealInfo\",\"name\":\"reveal\",\"type\":\"tuple\"},{\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"},{\"internalType\":\"uint16\",\"name\":\"referral\",\"type\":\"uint16\"}],\"name\":\"initializeStake\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pendingOwner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"}],\"name\":\"queueStake\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"stakeRequests\",\"outputs\":[{\"internalType\":\"enum AcreBitcoinDepositor.StakeRequestState\",\"name\":\"state\",\"type\":\"uint8\"},{\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"},{\"internalType\":\"uint88\",\"name\":\"queuedAmount\",\"type\":\"uint88\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"stbtc\",\"outputs\":[{\"internalType\":\"contract stBTC\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"tbtcToken\",\"outputs\":[{\"internalType\":\"contract IERC20\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"tbtcVault\",\"outputs\":[{\"internalType\":\"contract ITBTCVault\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint64\",\"name\":\"newDepositorFeeDivisor\",\"type\":\"uint64\"}],\"name\":\"updateDepositorFeeDivisor\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"errors\":{\"AddressEmptyCode(address)\":[{\"details\":\"There's no code at `target` (it is not a contract).\"}],\"AddressInsufficientBalance(address)\":[{\"details\":\"The ETH balance of the account is not enough to perform the operation.\"}],\"BridgingCompletionAlreadyNotified()\":[{\"details\":\"Attempted to notify a bridging completion, while it was already notified.\"}],\"BridgingFinalizationAlreadyCalled()\":[{\"details\":\"Attempted to call bridging finalization for a stake request for which the function was already called.\"}],\"BridgingNotCompleted()\":[{\"details\":\"Attempted to finalize a stake request, while bridging completion has not been notified yet.\"}],\"CallerNotStaker()\":[{\"details\":\"Attempted to call function by an account that is not the staker.\"}],\"DepositorFeeExceedsBridgedAmount(uint256,uint256)\":[{\"details\":\"Calculated depositor fee exceeds the amount of minted tBTC tokens.\"}],\"FailedInnerCall()\":[{\"details\":\"A call to an address target failed. The target may have reverted.\"}],\"InsufficientTbtcBalance(uint256,uint256)\":[{\"details\":\"Attempted to finalize bridging with depositor's contract tBTC balance lower than the calculated bridged tBTC amount. This error means that Governance should top-up the tBTC reserve for bridging fees approximation.\"}],\"OwnableInvalidOwner(address)\":[{\"details\":\"The owner is not a valid owner account. (eg. `address(0)`)\"}],\"OwnableUnauthorizedAccount(address)\":[{\"details\":\"The caller account is not authorized to perform an operation.\"}],\"SafeCastOverflowedUintDowncast(uint8,uint256)\":[{\"details\":\"Value doesn't fit in an uint of `bits` size.\"}],\"SafeERC20FailedOperation(address)\":[{\"details\":\"An operation with an ERC20 token failed.\"}],\"StakeRequestNotQueued()\":[{\"details\":\"Attempted to finalize or cancel a stake request that was not added to the queue, or was already finalized or cancelled.\"}],\"StakerIsZeroAddress()\":[{\"details\":\"Staker address is zero.\"}],\"UnexpectedStakeRequestState(uint8,uint8)\":[{\"details\":\"Attempted to execute function for stake request in unexpected current state.\"}]},\"events\":{\"BridgingCompleted(uint256,address,uint16,uint256,uint256)\":{\"params\":{\"bridgedAmount\":\"Amount of tBTC tokens that was bridged by the tBTC bridge.\",\"caller\":\"Address that notified about bridging completion.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"depositorFee\":\"Depositor fee amount.\",\"referral\":\"Identifier of a partner in the referral program.\"}},\"DepositorFeeDivisorUpdated(uint64)\":{\"params\":{\"depositorFeeDivisor\":\"New value of the depositor fee divisor.\"}},\"StakeRequestCancelledFromQueue(uint256,address,uint256)\":{\"params\":{\"amountToStake\":\"Amount of queued tBTC tokens that got cancelled.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"staker\":\"Address of the staker.\"}},\"StakeRequestFinalized(uint256,address,uint256)\":{\"details\":\"Deposit details can be fetched from {{ ERC4626.Deposit }} event emitted in the same transaction.\",\"params\":{\"caller\":\"Address that finalized the stake request.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"stakedAmount\":\"Amount of staked tBTC tokens.\"}},\"StakeRequestFinalizedFromQueue(uint256,address,uint256)\":{\"details\":\"Deposit details can be fetched from {{ ERC4626.Deposit }} event emitted in the same transaction.\",\"params\":{\"caller\":\"Address that finalized the stake request.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"stakedAmount\":\"Amount of staked tBTC tokens.\"}},\"StakeRequestInitialized(uint256,address,address)\":{\"details\":\"Deposit details can be fetched from {{ Bridge.DepositRevealed }} event emitted in the same transaction.\",\"params\":{\"caller\":\"Address that initialized the stake request.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"staker\":\"The address to which the stBTC shares will be minted.\"}},\"StakeRequestQueued(uint256,address,uint256)\":{\"params\":{\"caller\":\"Address that finalized the stake request.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"queuedAmount\":\"Amount of queued tBTC tokens.\"}}},\"kind\":\"dev\",\"methods\":{\"acceptOwnership()\":{\"details\":\"The new owner accepts the ownership transfer.\"},\"cancelQueuedStake(uint256)\":{\"details\":\"This function can be called only after the stake request was added to queue.Only staker provided in the extra data of the stake request can call this function.\",\"params\":{\"depositKey\":\"Deposit key identifying the deposit.\"}},\"constructor\":{\"params\":{\"_stbtc\":\"stBTC contract instance.\",\"_tbtcToken\":\"tBTC token contract instance.\",\"bridge\":\"tBTC Bridge contract instance.\",\"tbtcVault\":\"tBTC Vault contract instance.\"}},\"decodeExtraData(bytes32)\":{\"details\":\"Unpacks the data from bytes32: 20 bytes of staker address and 2 bytes of referral, 10 bytes of trailing zeros.\",\"params\":{\"extraData\":\"Encoded extra data.\"},\"returns\":{\"referral\":\"Data used for referral program.\",\"staker\":\"The address to which the stBTC shares will be minted.\"}},\"encodeExtraData(address,uint16)\":{\"details\":\"Packs the data to bytes32: 20 bytes of staker address and 2 bytes of referral, 10 bytes of trailing zeros.\",\"params\":{\"referral\":\"Data used for referral program.\",\"staker\":\"The address to which the stBTC shares will be minted.\"},\"returns\":{\"_0\":\"Encoded extra data.\"}},\"finalizeQueuedStake(uint256)\":{\"params\":{\"depositKey\":\"Deposit key identifying the deposit.\"}},\"finalizeStake(uint256)\":{\"details\":\"In case depositing in stBTC vault fails (e.g. because of the maximum deposit limit being reached), the `queueStake` function should be called to add the stake request to the staking queue.\",\"params\":{\"depositKey\":\"Deposit key identifying the deposit.\"}},\"initializeStake((bytes4,bytes,bytes,bytes4),(uint32,bytes8,bytes20,bytes20,bytes4,address),address,uint16)\":{\"details\":\"Requirements: - The revealed vault address must match the TBTCVault address, - All requirements from {Bridge#revealDepositWithExtraData} function must be met. - `staker` must be the staker address used in the P2(W)SH BTC deposit transaction as part of the extra data. - `referral` must be the referral info used in the P2(W)SH BTC deposit transaction as part of the extra data. - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex` can be revealed only one time.\",\"params\":{\"fundingTx\":\"Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.\",\"referral\":\"Data used for referral program.\",\"reveal\":\"Deposit reveal data, see `IBridgeTypes.DepositRevealInfo`.\",\"staker\":\"The address to which the stBTC shares will be minted.\"}},\"owner()\":{\"details\":\"Returns the address of the current owner.\"},\"pendingOwner()\":{\"details\":\"Returns the address of the pending owner.\"},\"queueStake(uint256)\":{\"details\":\"It queues the stake request, until the stBTC vault is ready to accept the deposit. The request must be finalized with `finalizeQueuedStake` after the limit is increased or other user withdraws their funds from the stBTC contract to make place for another deposit. The staker has a possibility to submit `cancelQueuedStake` that will withdraw the minted tBTC token and abort staking process.\",\"params\":{\"depositKey\":\"Deposit key identifying the deposit.\"}},\"renounceOwnership()\":{\"details\":\"Leaves the contract without owner. It will not be possible to call `onlyOwner` functions. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby disabling any functionality that is only available to the owner.\"},\"transferOwnership(address)\":{\"details\":\"Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. Can only be called by the current owner.\"},\"updateDepositorFeeDivisor(uint64)\":{\"params\":{\"newDepositorFeeDivisor\":\"New depositor fee divisor value.\"}}},\"stateVariables\":{\"depositorFeeDivisor\":{\"details\":\"That fee is computed as follows: `depositorFee = depositedAmount / depositorFeeDivisor` for example, if the depositor fee needs to be 2% of each deposit, the `depositorFeeDivisor` should be set to `50` because `1/50 = 0.02 = 2%`.\"},\"stakeRequests\":{\"details\":\"The key is a deposit key identifying the deposit.\"}},\"title\":\"Acre Bitcoin Depositor contract.\",\"version\":1},\"userdoc\":{\"errors\":{\"StbtcZeroAddress()\":[{\"notice\":\"Reverts if the stBTC address is zero.\"}],\"TbtcTokenZeroAddress()\":[{\"notice\":\"Reverts if the tBTC Token address is zero.\"}]},\"events\":{\"BridgingCompleted(uint256,address,uint16,uint256,uint256)\":{\"notice\":\"Emitted when bridging completion has been notified.\"},\"DepositorFeeDivisorUpdated(uint64)\":{\"notice\":\"Emitted when a depositor fee divisor is updated.\"},\"StakeRequestCancelledFromQueue(uint256,address,uint256)\":{\"notice\":\"Emitted when a queued stake request is cancelled.\"},\"StakeRequestFinalized(uint256,address,uint256)\":{\"notice\":\"Emitted when a stake request is finalized.\"},\"StakeRequestFinalizedFromQueue(uint256,address,uint256)\":{\"notice\":\"Emitted when a stake request is finalized from the queue.\"},\"StakeRequestInitialized(uint256,address,address)\":{\"notice\":\"Emitted when a stake request is initialized.\"},\"StakeRequestQueued(uint256,address,uint256)\":{\"notice\":\"Emitted when a stake request is queued.\"}},\"kind\":\"user\",\"methods\":{\"SATOSHI_MULTIPLIER()\":{\"notice\":\"Multiplier to convert satoshi to TBTC token units.\"},\"bridge()\":{\"notice\":\"Bridge contract address.\"},\"cancelQueuedStake(uint256)\":{\"notice\":\"Cancel queued stake. The function can be called by the staker to recover tBTC that cannot be finalized to stake in stBTC contract due to a deposit limit being reached.\"},\"constructor\":{\"notice\":\"Acre Bitcoin Depositor contract constructor.\"},\"decodeExtraData(bytes32)\":{\"notice\":\"Decodes staker address and referral from extra data.\"},\"depositorFeeDivisor()\":{\"notice\":\"Divisor used to compute the depositor fee taken from each deposit and transferred to the treasury upon stake request finalization.\"},\"encodeExtraData(address,uint16)\":{\"notice\":\"Encodes staker address and referral as extra data.\"},\"finalizeQueuedStake(uint256)\":{\"notice\":\"This function should be called for previously queued stake request, when stBTC vault is able to accept a deposit.\"},\"finalizeStake(uint256)\":{\"notice\":\"This function should be called for previously initialized stake request, after tBTC bridging process was finalized. It stakes the tBTC from the given deposit into stBTC, emitting the stBTC shares to the staker specified in the deposit extra data and using the referral provided in the extra data.\"},\"initializeStake((bytes4,bytes,bytes,bytes4),(uint32,bytes8,bytes20,bytes20,bytes4,address),address,uint16)\":{\"notice\":\"This function allows staking process initialization for a Bitcoin deposit made by an user with a P2(W)SH transaction. It uses the supplied information to reveal a deposit to the tBTC Bridge contract.\"},\"queueStake(uint256)\":{\"notice\":\"This function should be called for previously initialized stake request, after tBTC bridging process was finalized, in case the `finalizeStake` failed due to stBTC vault deposit limit being reached.\"},\"stakeRequests(uint256)\":{\"notice\":\"Mapping of stake requests.\"},\"stbtc()\":{\"notice\":\"stBTC contract.\"},\"tbtcToken()\":{\"notice\":\"tBTC Token contract.\"},\"tbtcVault()\":{\"notice\":\"TBTCVault contract address.\"},\"updateDepositorFeeDivisor(uint64)\":{\"notice\":\"Updates the depositor fee divisor.\"}},\"notice\":\"The contract integrates Acre staking with tBTC minting. User who wants to stake BTC in Acre should submit a Bitcoin transaction to the most recently created off-chain ECDSA wallets of the tBTC Bridge using pay-to-script-hash (P2SH) or pay-to-witness-script-hash (P2WSH) containing hashed information about this Depositor contract address, and staker's Ethereum address. Then, the staker initiates tBTC minting by revealing their Ethereum address along with their deposit blinding factor, refund public key hash and refund locktime on the tBTC Bridge through this Depositor contract. The off-chain ECDSA wallet and Optimistic Minting bots listen for these sorts of messages and when they get one, they check the Bitcoin network to make sure the deposit lines up. Majority of tBTC minting is finalized by the Optimistic Minting process, where Minter bot initializes minting process and if there is no veto from the Guardians, the process is finalized and tBTC minted to the Depositor address. If the revealed deposit is not handled by the Optimistic Minting process the off-chain ECDSA wallet may decide to pick the deposit transaction for sweeping, and when the sweep operation is confirmed on the Bitcoin network, the tBTC Bridge and tBTC vault mint the tBTC token to the Depositor address. After tBTC is minted to the Depositor, on the stake finalization tBTC is staked in stBTC contract and stBTC shares are emitted to the staker.\",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/AcreBitcoinDepositor.sol\":\"AcreBitcoinDepositor\"},\"evmVersion\":\"paris\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":1000},\"remappings\":[]},\"sources\":{\"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\":{\"content\":\"pragma solidity ^0.8.4;\\n\\n/** @title BitcoinSPV */\\n/** @author Summa (https://summa.one) */\\n\\nimport {BytesLib} from \\\"./BytesLib.sol\\\";\\nimport {SafeMath} from \\\"./SafeMath.sol\\\";\\n\\nlibrary BTCUtils {\\n using BytesLib for bytes;\\n using SafeMath for uint256;\\n\\n // The target at minimum Difficulty. Also the target of the genesis block\\n uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000;\\n\\n uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds\\n uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks\\n\\n uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\\n\\n /* ***** */\\n /* UTILS */\\n /* ***** */\\n\\n /// @notice Determines the length of a VarInt in bytes\\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\\n /// @param _flag The first byte of a VarInt\\n /// @return The number of non-flag bytes in the VarInt\\n function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) {\\n return determineVarIntDataLengthAt(_flag, 0);\\n }\\n\\n /// @notice Determines the length of a VarInt in bytes\\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\\n /// @param _b The byte array containing a VarInt\\n /// @param _at The position of the VarInt in the array\\n /// @return The number of non-flag bytes in the VarInt\\n function determineVarIntDataLengthAt(bytes memory _b, uint256 _at) internal pure returns (uint8) {\\n if (uint8(_b[_at]) == 0xff) {\\n return 8; // one-byte flag, 8 bytes data\\n }\\n if (uint8(_b[_at]) == 0xfe) {\\n return 4; // one-byte flag, 4 bytes data\\n }\\n if (uint8(_b[_at]) == 0xfd) {\\n return 2; // one-byte flag, 2 bytes data\\n }\\n\\n return 0; // flag is data\\n }\\n\\n /// @notice Parse a VarInt into its data length and the number it represents\\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\\n /// Caller SHOULD explicitly handle this case (or bubble it up)\\n /// @param _b A byte-string starting with a VarInt\\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\\n function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) {\\n return parseVarIntAt(_b, 0);\\n }\\n\\n /// @notice Parse a VarInt into its data length and the number it represents\\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\\n /// Caller SHOULD explicitly handle this case (or bubble it up)\\n /// @param _b A byte-string containing a VarInt\\n /// @param _at The position of the VarInt\\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\\n function parseVarIntAt(bytes memory _b, uint256 _at) internal pure returns (uint256, uint256) {\\n uint8 _dataLen = determineVarIntDataLengthAt(_b, _at);\\n\\n if (_dataLen == 0) {\\n return (0, uint8(_b[_at]));\\n }\\n if (_b.length < 1 + _dataLen + _at) {\\n return (ERR_BAD_ARG, 0);\\n }\\n uint256 _number;\\n if (_dataLen == 2) {\\n _number = reverseUint16(uint16(_b.slice2(1 + _at)));\\n } else if (_dataLen == 4) {\\n _number = reverseUint32(uint32(_b.slice4(1 + _at)));\\n } else if (_dataLen == 8) {\\n _number = reverseUint64(uint64(_b.slice8(1 + _at)));\\n }\\n return (_dataLen, _number);\\n }\\n\\n /// @notice Changes the endianness of a byte array\\n /// @dev Returns a new, backwards, bytes\\n /// @param _b The bytes to reverse\\n /// @return The reversed bytes\\n function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) {\\n bytes memory _newValue = new bytes(_b.length);\\n\\n for (uint i = 0; i < _b.length; i++) {\\n _newValue[_b.length - i - 1] = _b[i];\\n }\\n\\n return _newValue;\\n }\\n\\n /// @notice Changes the endianness of a uint256\\n /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel\\n /// @param _b The unsigned integer to reverse\\n /// @return v The reversed value\\n function reverseUint256(uint256 _b) internal pure returns (uint256 v) {\\n v = _b;\\n\\n // swap bytes\\n v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |\\n ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);\\n // swap 2-byte long pairs\\n v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |\\n ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);\\n // swap 4-byte long pairs\\n v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |\\n ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);\\n // swap 8-byte long pairs\\n v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |\\n ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);\\n // swap 16-byte long pairs\\n v = (v >> 128) | (v << 128);\\n }\\n\\n /// @notice Changes the endianness of a uint64\\n /// @param _b The unsigned integer to reverse\\n /// @return v The reversed value\\n function reverseUint64(uint64 _b) internal pure returns (uint64 v) {\\n v = _b;\\n\\n // swap bytes\\n v = ((v >> 8) & 0x00FF00FF00FF00FF) |\\n ((v & 0x00FF00FF00FF00FF) << 8);\\n // swap 2-byte long pairs\\n v = ((v >> 16) & 0x0000FFFF0000FFFF) |\\n ((v & 0x0000FFFF0000FFFF) << 16);\\n // swap 4-byte long pairs\\n v = (v >> 32) | (v << 32);\\n }\\n\\n /// @notice Changes the endianness of a uint32\\n /// @param _b The unsigned integer to reverse\\n /// @return v The reversed value\\n function reverseUint32(uint32 _b) internal pure returns (uint32 v) {\\n v = _b;\\n\\n // swap bytes\\n v = ((v >> 8) & 0x00FF00FF) |\\n ((v & 0x00FF00FF) << 8);\\n // swap 2-byte long pairs\\n v = (v >> 16) | (v << 16);\\n }\\n\\n /// @notice Changes the endianness of a uint24\\n /// @param _b The unsigned integer to reverse\\n /// @return v The reversed value\\n function reverseUint24(uint24 _b) internal pure returns (uint24 v) {\\n v = (_b << 16) | (_b & 0x00FF00) | (_b >> 16);\\n }\\n\\n /// @notice Changes the endianness of a uint16\\n /// @param _b The unsigned integer to reverse\\n /// @return v The reversed value\\n function reverseUint16(uint16 _b) internal pure returns (uint16 v) {\\n v = (_b << 8) | (_b >> 8);\\n }\\n\\n\\n /// @notice Converts big-endian bytes to a uint\\n /// @dev Traverses the byte array and sums the bytes\\n /// @param _b The big-endian bytes-encoded integer\\n /// @return The integer representation\\n function bytesToUint(bytes memory _b) internal pure returns (uint256) {\\n uint256 _number;\\n\\n for (uint i = 0; i < _b.length; i++) {\\n _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));\\n }\\n\\n return _number;\\n }\\n\\n /// @notice Get the last _num bytes from a byte array\\n /// @param _b The byte array to slice\\n /// @param _num The number of bytes to extract from the end\\n /// @return The last _num bytes of _b\\n function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) {\\n uint256 _start = _b.length.sub(_num);\\n\\n return _b.slice(_start, _num);\\n }\\n\\n /// @notice Implements bitcoin's hash160 (rmd160(sha2()))\\n /// @dev abi.encodePacked changes the return to bytes instead of bytes32\\n /// @param _b The pre-image\\n /// @return The digest\\n function hash160(bytes memory _b) internal pure returns (bytes memory) {\\n return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));\\n }\\n\\n /// @notice Implements bitcoin's hash160 (sha2 + ripemd160)\\n /// @dev sha2 precompile at address(2), ripemd160 at address(3)\\n /// @param _b The pre-image\\n /// @return res The digest\\n function hash160View(bytes memory _b) internal view returns (bytes20 res) {\\n // solium-disable-next-line security/no-inline-assembly\\n assembly {\\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\\n pop(staticcall(gas(), 3, 0x00, 32, 0x00, 32))\\n // read from position 12 = 0c\\n res := mload(0x0c)\\n }\\n }\\n\\n /// @notice Implements bitcoin's hash256 (double sha2)\\n /// @dev abi.encodePacked changes the return to bytes instead of bytes32\\n /// @param _b The pre-image\\n /// @return The digest\\n function hash256(bytes memory _b) internal pure returns (bytes32) {\\n return sha256(abi.encodePacked(sha256(_b)));\\n }\\n\\n /// @notice Implements bitcoin's hash256 (double sha2)\\n /// @dev sha2 is precompiled smart contract located at address(2)\\n /// @param _b The pre-image\\n /// @return res The digest\\n function hash256View(bytes memory _b) internal view returns (bytes32 res) {\\n // solium-disable-next-line security/no-inline-assembly\\n assembly {\\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\\n res := mload(0x00)\\n }\\n }\\n\\n /// @notice Implements bitcoin's hash256 on a pair of bytes32\\n /// @dev sha2 is precompiled smart contract located at address(2)\\n /// @param _a The first bytes32 of the pre-image\\n /// @param _b The second bytes32 of the pre-image\\n /// @return res The digest\\n function hash256Pair(bytes32 _a, bytes32 _b) internal view returns (bytes32 res) {\\n // solium-disable-next-line security/no-inline-assembly\\n assembly {\\n mstore(0x00, _a)\\n mstore(0x20, _b)\\n pop(staticcall(gas(), 2, 0x00, 64, 0x00, 32))\\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\\n res := mload(0x00)\\n }\\n }\\n\\n /// @notice Implements bitcoin's hash256 (double sha2)\\n /// @dev sha2 is precompiled smart contract located at address(2)\\n /// @param _b The array containing the pre-image\\n /// @param at The start of the pre-image\\n /// @param len The length of the pre-image\\n /// @return res The digest\\n function hash256Slice(\\n bytes memory _b,\\n uint256 at,\\n uint256 len\\n ) internal view returns (bytes32 res) {\\n // solium-disable-next-line security/no-inline-assembly\\n assembly {\\n pop(staticcall(gas(), 2, add(_b, add(32, at)), len, 0x00, 32))\\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\\n res := mload(0x00)\\n }\\n }\\n\\n /* ************ */\\n /* Legacy Input */\\n /* ************ */\\n\\n /// @notice Extracts the nth input from the vin (0-indexed)\\n /// @dev Iterates over the vin. If you need to extract several, write a custom function\\n /// @param _vin The vin as a tightly-packed byte array\\n /// @param _index The 0-indexed location of the input to extract\\n /// @return The input as a byte array\\n function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) {\\n uint256 _varIntDataLen;\\n uint256 _nIns;\\n\\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\\n require(_varIntDataLen != ERR_BAD_ARG, \\\"Read overrun during VarInt parsing\\\");\\n require(_index < _nIns, \\\"Vin read overrun\\\");\\n\\n uint256 _len = 0;\\n uint256 _offset = 1 + _varIntDataLen;\\n\\n for (uint256 _i = 0; _i < _index; _i ++) {\\n _len = determineInputLengthAt(_vin, _offset);\\n require(_len != ERR_BAD_ARG, \\\"Bad VarInt in scriptSig\\\");\\n _offset = _offset + _len;\\n }\\n\\n _len = determineInputLengthAt(_vin, _offset);\\n require(_len != ERR_BAD_ARG, \\\"Bad VarInt in scriptSig\\\");\\n return _vin.slice(_offset, _len);\\n }\\n\\n /// @notice Determines whether an input is legacy\\n /// @dev False if no scriptSig, otherwise True\\n /// @param _input The input\\n /// @return True for legacy, False for witness\\n function isLegacyInput(bytes memory _input) internal pure returns (bool) {\\n return _input[36] != hex\\\"00\\\";\\n }\\n\\n /// @notice Determines the length of a scriptSig in an input\\n /// @dev Will return 0 if passed a witness input.\\n /// @param _input The LEGACY input\\n /// @return The length of the script sig\\n function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) {\\n return extractScriptSigLenAt(_input, 0);\\n }\\n\\n /// @notice Determines the length of a scriptSig in an input\\n /// starting at the specified position\\n /// @dev Will return 0 if passed a witness input.\\n /// @param _input The byte array containing the LEGACY input\\n /// @param _at The position of the input in the array\\n /// @return The length of the script sig\\n function extractScriptSigLenAt(bytes memory _input, uint256 _at) internal pure returns (uint256, uint256) {\\n if (_input.length < 37 + _at) {\\n return (ERR_BAD_ARG, 0);\\n }\\n\\n uint256 _varIntDataLen;\\n uint256 _scriptSigLen;\\n (_varIntDataLen, _scriptSigLen) = parseVarIntAt(_input, _at + 36);\\n\\n return (_varIntDataLen, _scriptSigLen);\\n }\\n\\n /// @notice Determines the length of an input from its scriptSig\\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\\n /// @param _input The input\\n /// @return The length of the input in bytes\\n function determineInputLength(bytes memory _input) internal pure returns (uint256) {\\n return determineInputLengthAt(_input, 0);\\n }\\n\\n /// @notice Determines the length of an input from its scriptSig,\\n /// starting at the specified position\\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\\n /// @param _input The byte array containing the input\\n /// @param _at The position of the input in the array\\n /// @return The length of the input in bytes\\n function determineInputLengthAt(bytes memory _input, uint256 _at) internal pure returns (uint256) {\\n uint256 _varIntDataLen;\\n uint256 _scriptSigLen;\\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLenAt(_input, _at);\\n if (_varIntDataLen == ERR_BAD_ARG) {\\n return ERR_BAD_ARG;\\n }\\n\\n return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;\\n }\\n\\n /// @notice Extracts the LE sequence bytes from an input\\n /// @dev Sequence is used for relative time locks\\n /// @param _input The LEGACY input\\n /// @return The sequence bytes (LE uint)\\n function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes4) {\\n uint256 _varIntDataLen;\\n uint256 _scriptSigLen;\\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\\n require(_varIntDataLen != ERR_BAD_ARG, \\\"Bad VarInt in scriptSig\\\");\\n return _input.slice4(36 + 1 + _varIntDataLen + _scriptSigLen);\\n }\\n\\n /// @notice Extracts the sequence from the input\\n /// @dev Sequence is a 4-byte little-endian number\\n /// @param _input The LEGACY input\\n /// @return The sequence number (big-endian uint)\\n function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) {\\n uint32 _leSeqence = uint32(extractSequenceLELegacy(_input));\\n uint32 _beSequence = reverseUint32(_leSeqence);\\n return _beSequence;\\n }\\n /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx\\n /// @dev Will return hex\\\"00\\\" if passed a witness input\\n /// @param _input The LEGACY input\\n /// @return The length-prepended scriptSig\\n function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) {\\n uint256 _varIntDataLen;\\n uint256 _scriptSigLen;\\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\\n require(_varIntDataLen != ERR_BAD_ARG, \\\"Bad VarInt in scriptSig\\\");\\n return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);\\n }\\n\\n\\n /* ************* */\\n /* Witness Input */\\n /* ************* */\\n\\n /// @notice Extracts the LE sequence bytes from an input\\n /// @dev Sequence is used for relative time locks\\n /// @param _input The WITNESS input\\n /// @return The sequence bytes (LE uint)\\n function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes4) {\\n return _input.slice4(37);\\n }\\n\\n /// @notice Extracts the sequence from the input in a tx\\n /// @dev Sequence is a 4-byte little-endian number\\n /// @param _input The WITNESS input\\n /// @return The sequence number (big-endian uint)\\n function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) {\\n uint32 _leSeqence = uint32(extractSequenceLEWitness(_input));\\n uint32 _inputeSequence = reverseUint32(_leSeqence);\\n return _inputeSequence;\\n }\\n\\n /// @notice Extracts the outpoint from the input in a tx\\n /// @dev 32-byte tx id with 4-byte index\\n /// @param _input The input\\n /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)\\n function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) {\\n return _input.slice(0, 36);\\n }\\n\\n /// @notice Extracts the outpoint tx id from an input\\n /// @dev 32-byte tx id\\n /// @param _input The input\\n /// @return The tx id (little-endian bytes)\\n function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) {\\n return _input.slice32(0);\\n }\\n\\n /// @notice Extracts the outpoint tx id from an input\\n /// starting at the specified position\\n /// @dev 32-byte tx id\\n /// @param _input The byte array containing the input\\n /// @param _at The position of the input\\n /// @return The tx id (little-endian bytes)\\n function extractInputTxIdLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes32) {\\n return _input.slice32(_at);\\n }\\n\\n /// @notice Extracts the LE tx input index from the input in a tx\\n /// @dev 4-byte tx index\\n /// @param _input The input\\n /// @return The tx index (little-endian bytes)\\n function extractTxIndexLE(bytes memory _input) internal pure returns (bytes4) {\\n return _input.slice4(32);\\n }\\n\\n /// @notice Extracts the LE tx input index from the input in a tx\\n /// starting at the specified position\\n /// @dev 4-byte tx index\\n /// @param _input The byte array containing the input\\n /// @param _at The position of the input\\n /// @return The tx index (little-endian bytes)\\n function extractTxIndexLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes4) {\\n return _input.slice4(32 + _at);\\n }\\n\\n /* ****** */\\n /* Output */\\n /* ****** */\\n\\n /// @notice Determines the length of an output\\n /// @dev Works with any properly formatted output\\n /// @param _output The output\\n /// @return The length indicated by the prefix, error if invalid length\\n function determineOutputLength(bytes memory _output) internal pure returns (uint256) {\\n return determineOutputLengthAt(_output, 0);\\n }\\n\\n /// @notice Determines the length of an output\\n /// starting at the specified position\\n /// @dev Works with any properly formatted output\\n /// @param _output The byte array containing the output\\n /// @param _at The position of the output\\n /// @return The length indicated by the prefix, error if invalid length\\n function determineOutputLengthAt(bytes memory _output, uint256 _at) internal pure returns (uint256) {\\n if (_output.length < 9 + _at) {\\n return ERR_BAD_ARG;\\n }\\n uint256 _varIntDataLen;\\n uint256 _scriptPubkeyLength;\\n (_varIntDataLen, _scriptPubkeyLength) = parseVarIntAt(_output, 8 + _at);\\n\\n if (_varIntDataLen == ERR_BAD_ARG) {\\n return ERR_BAD_ARG;\\n }\\n\\n // 8-byte value, 1-byte for tag itself\\n return 8 + 1 + _varIntDataLen + _scriptPubkeyLength;\\n }\\n\\n /// @notice Extracts the output at a given index in the TxOuts vector\\n /// @dev Iterates over the vout. If you need to extract multiple, write a custom function\\n /// @param _vout The _vout to extract from\\n /// @param _index The 0-indexed location of the output to extract\\n /// @return The specified output\\n function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) {\\n uint256 _varIntDataLen;\\n uint256 _nOuts;\\n\\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\\n require(_varIntDataLen != ERR_BAD_ARG, \\\"Read overrun during VarInt parsing\\\");\\n require(_index < _nOuts, \\\"Vout read overrun\\\");\\n\\n uint256 _len = 0;\\n uint256 _offset = 1 + _varIntDataLen;\\n\\n for (uint256 _i = 0; _i < _index; _i ++) {\\n _len = determineOutputLengthAt(_vout, _offset);\\n require(_len != ERR_BAD_ARG, \\\"Bad VarInt in scriptPubkey\\\");\\n _offset += _len;\\n }\\n\\n _len = determineOutputLengthAt(_vout, _offset);\\n require(_len != ERR_BAD_ARG, \\\"Bad VarInt in scriptPubkey\\\");\\n return _vout.slice(_offset, _len);\\n }\\n\\n /// @notice Extracts the value bytes from the output in a tx\\n /// @dev Value is an 8-byte little-endian number\\n /// @param _output The output\\n /// @return The output value as LE bytes\\n function extractValueLE(bytes memory _output) internal pure returns (bytes8) {\\n return _output.slice8(0);\\n }\\n\\n /// @notice Extracts the value from the output in a tx\\n /// @dev Value is an 8-byte little-endian number\\n /// @param _output The output\\n /// @return The output value\\n function extractValue(bytes memory _output) internal pure returns (uint64) {\\n uint64 _leValue = uint64(extractValueLE(_output));\\n uint64 _beValue = reverseUint64(_leValue);\\n return _beValue;\\n }\\n\\n /// @notice Extracts the value from the output in a tx\\n /// @dev Value is an 8-byte little-endian number\\n /// @param _output The byte array containing the output\\n /// @param _at The starting index of the output in the array\\n /// @return The output value\\n function extractValueAt(bytes memory _output, uint256 _at) internal pure returns (uint64) {\\n uint64 _leValue = uint64(_output.slice8(_at));\\n uint64 _beValue = reverseUint64(_leValue);\\n return _beValue;\\n }\\n\\n /// @notice Extracts the data from an op return output\\n /// @dev Returns hex\\\"\\\" if no data or not an op return\\n /// @param _output The output\\n /// @return Any data contained in the opreturn output, null if not an op return\\n function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) {\\n if (_output[9] != hex\\\"6a\\\") {\\n return hex\\\"\\\";\\n }\\n bytes1 _dataLen = _output[10];\\n return _output.slice(11, uint256(uint8(_dataLen)));\\n }\\n\\n /// @notice Extracts the hash from the output script\\n /// @dev Determines type by the length prefix and validates format\\n /// @param _output The output\\n /// @return The hash committed to by the pk_script, or null for errors\\n function extractHash(bytes memory _output) internal pure returns (bytes memory) {\\n return extractHashAt(_output, 8, _output.length - 8);\\n }\\n\\n /// @notice Extracts the hash from the output script\\n /// @dev Determines type by the length prefix and validates format\\n /// @param _output The byte array containing the output\\n /// @param _at The starting index of the output script in the array\\n /// (output start + 8)\\n /// @param _len The length of the output script\\n /// (output length - 8)\\n /// @return The hash committed to by the pk_script, or null for errors\\n function extractHashAt(\\n bytes memory _output,\\n uint256 _at,\\n uint256 _len\\n ) internal pure returns (bytes memory) {\\n uint8 _scriptLen = uint8(_output[_at]);\\n\\n // don't have to worry about overflow here.\\n // if _scriptLen + 1 overflows, then output length would have to be < 1\\n // for this check to pass. if it's < 1, then we errored when assigning\\n // _scriptLen\\n if (_scriptLen + 1 != _len) {\\n return hex\\\"\\\";\\n }\\n\\n if (uint8(_output[_at + 1]) == 0) {\\n if (_scriptLen < 2) {\\n return hex\\\"\\\";\\n }\\n uint256 _payloadLen = uint8(_output[_at + 2]);\\n // Check for maliciously formatted witness outputs.\\n // No need to worry about underflow as long b/c of the `< 2` check\\n if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) {\\n return hex\\\"\\\";\\n }\\n return _output.slice(_at + 3, _payloadLen);\\n } else {\\n bytes3 _tag = _output.slice3(_at);\\n // p2pkh\\n if (_tag == hex\\\"1976a9\\\") {\\n // Check for maliciously formatted p2pkh\\n // No need to worry about underflow, b/c of _scriptLen check\\n if (uint8(_output[_at + 3]) != 0x14 ||\\n _output.slice2(_at + _len - 2) != hex\\\"88ac\\\") {\\n return hex\\\"\\\";\\n }\\n return _output.slice(_at + 4, 20);\\n //p2sh\\n } else if (_tag == hex\\\"17a914\\\") {\\n // Check for maliciously formatted p2sh\\n // No need to worry about underflow, b/c of _scriptLen check\\n if (uint8(_output[_at + _len - 1]) != 0x87) {\\n return hex\\\"\\\";\\n }\\n return _output.slice(_at + 3, 20);\\n }\\n }\\n return hex\\\"\\\"; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */\\n }\\n\\n /* ********** */\\n /* Witness TX */\\n /* ********** */\\n\\n\\n /// @notice Checks that the vin passed up is properly formatted\\n /// @dev Consider a vin with a valid vout in its scriptsig\\n /// @param _vin Raw bytes length-prefixed input vector\\n /// @return True if it represents a validly formatted vin\\n function validateVin(bytes memory _vin) internal pure returns (bool) {\\n uint256 _varIntDataLen;\\n uint256 _nIns;\\n\\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\\n\\n // Not valid if it says there are too many or no inputs\\n if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) {\\n return false;\\n }\\n\\n uint256 _offset = 1 + _varIntDataLen;\\n\\n for (uint256 i = 0; i < _nIns; i++) {\\n // If we're at the end, but still expect more\\n if (_offset >= _vin.length) {\\n return false;\\n }\\n\\n // Grab the next input and determine its length.\\n uint256 _nextLen = determineInputLengthAt(_vin, _offset);\\n if (_nextLen == ERR_BAD_ARG) {\\n return false;\\n }\\n\\n // Increase the offset by that much\\n _offset += _nextLen;\\n }\\n\\n // Returns false if we're not exactly at the end\\n return _offset == _vin.length;\\n }\\n\\n /// @notice Checks that the vout passed up is properly formatted\\n /// @dev Consider a vout with a valid scriptpubkey\\n /// @param _vout Raw bytes length-prefixed output vector\\n /// @return True if it represents a validly formatted vout\\n function validateVout(bytes memory _vout) internal pure returns (bool) {\\n uint256 _varIntDataLen;\\n uint256 _nOuts;\\n\\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\\n\\n // Not valid if it says there are too many or no outputs\\n if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) {\\n return false;\\n }\\n\\n uint256 _offset = 1 + _varIntDataLen;\\n\\n for (uint256 i = 0; i < _nOuts; i++) {\\n // If we're at the end, but still expect more\\n if (_offset >= _vout.length) {\\n return false;\\n }\\n\\n // Grab the next output and determine its length.\\n // Increase the offset by that much\\n uint256 _nextLen = determineOutputLengthAt(_vout, _offset);\\n if (_nextLen == ERR_BAD_ARG) {\\n return false;\\n }\\n\\n _offset += _nextLen;\\n }\\n\\n // Returns false if we're not exactly at the end\\n return _offset == _vout.length;\\n }\\n\\n\\n\\n /* ************ */\\n /* Block Header */\\n /* ************ */\\n\\n /// @notice Extracts the transaction merkle root from a block header\\n /// @dev Use verifyHash256Merkle to verify proofs with this root\\n /// @param _header The header\\n /// @return The merkle root (little-endian)\\n function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes32) {\\n return _header.slice32(36);\\n }\\n\\n /// @notice Extracts the target from a block header\\n /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\\n /// @param _header The header\\n /// @return The target threshold\\n function extractTarget(bytes memory _header) internal pure returns (uint256) {\\n return extractTargetAt(_header, 0);\\n }\\n\\n /// @notice Extracts the target from a block header\\n /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\\n /// @param _header The array containing the header\\n /// @param at The start of the header\\n /// @return The target threshold\\n function extractTargetAt(bytes memory _header, uint256 at) internal pure returns (uint256) {\\n uint24 _m = uint24(_header.slice3(72 + at));\\n uint8 _e = uint8(_header[75 + at]);\\n uint256 _mantissa = uint256(reverseUint24(_m));\\n uint _exponent = _e - 3;\\n\\n return _mantissa * (256 ** _exponent);\\n }\\n\\n /// @notice Calculate difficulty from the difficulty 1 target and current target\\n /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet\\n /// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\\n /// @param _target The current target\\n /// @return The block difficulty (bdiff)\\n function calculateDifficulty(uint256 _target) internal pure returns (uint256) {\\n // Difficulty 1 calculated from 0x1d00ffff\\n return DIFF1_TARGET.div(_target);\\n }\\n\\n /// @notice Extracts the previous block's hash from a block header\\n /// @dev Block headers do NOT include block number :(\\n /// @param _header The header\\n /// @return The previous block's hash (little-endian)\\n function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes32) {\\n return _header.slice32(4);\\n }\\n\\n /// @notice Extracts the previous block's hash from a block header\\n /// @dev Block headers do NOT include block number :(\\n /// @param _header The array containing the header\\n /// @param at The start of the header\\n /// @return The previous block's hash (little-endian)\\n function extractPrevBlockLEAt(\\n bytes memory _header,\\n uint256 at\\n ) internal pure returns (bytes32) {\\n return _header.slice32(4 + at);\\n }\\n\\n /// @notice Extracts the timestamp from a block header\\n /// @dev Time is not 100% reliable\\n /// @param _header The header\\n /// @return The timestamp (little-endian bytes)\\n function extractTimestampLE(bytes memory _header) internal pure returns (bytes4) {\\n return _header.slice4(68);\\n }\\n\\n /// @notice Extracts the timestamp from a block header\\n /// @dev Time is not 100% reliable\\n /// @param _header The header\\n /// @return The timestamp (uint)\\n function extractTimestamp(bytes memory _header) internal pure returns (uint32) {\\n return reverseUint32(uint32(extractTimestampLE(_header)));\\n }\\n\\n /// @notice Extracts the expected difficulty from a block header\\n /// @dev Does NOT verify the work\\n /// @param _header The header\\n /// @return The difficulty as an integer\\n function extractDifficulty(bytes memory _header) internal pure returns (uint256) {\\n return calculateDifficulty(extractTarget(_header));\\n }\\n\\n /// @notice Concatenates and hashes two inputs for merkle proving\\n /// @param _a The first hash\\n /// @param _b The second hash\\n /// @return The double-sha256 of the concatenated hashes\\n function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal view returns (bytes32) {\\n return hash256View(abi.encodePacked(_a, _b));\\n }\\n\\n /// @notice Concatenates and hashes two inputs for merkle proving\\n /// @param _a The first hash\\n /// @param _b The second hash\\n /// @return The double-sha256 of the concatenated hashes\\n function _hash256MerkleStep(bytes32 _a, bytes32 _b) internal view returns (bytes32) {\\n return hash256Pair(_a, _b);\\n }\\n\\n\\n /// @notice Verifies a Bitcoin-style merkle tree\\n /// @dev Leaves are 0-indexed. Inefficient version.\\n /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root\\n /// @param _index The index of the leaf\\n /// @return true if the proof is valid, else false\\n function verifyHash256Merkle(bytes memory _proof, uint _index) internal view returns (bool) {\\n // Not an even number of hashes\\n if (_proof.length % 32 != 0) {\\n return false;\\n }\\n\\n // Special case for coinbase-only blocks\\n if (_proof.length == 32) {\\n return true;\\n }\\n\\n // Should never occur\\n if (_proof.length == 64) {\\n return false;\\n }\\n\\n bytes32 _root = _proof.slice32(_proof.length - 32);\\n bytes32 _current = _proof.slice32(0);\\n bytes memory _tree = _proof.slice(32, _proof.length - 64);\\n\\n return verifyHash256Merkle(_current, _tree, _root, _index);\\n }\\n\\n /// @notice Verifies a Bitcoin-style merkle tree\\n /// @dev Leaves are 0-indexed. Efficient version.\\n /// @param _leaf The leaf of the proof. LE sha256 hash.\\n /// @param _tree The intermediate nodes in the proof.\\n /// Tightly packed LE sha256 hashes.\\n /// @param _root The root of the proof. LE sha256 hash.\\n /// @param _index The index of the leaf\\n /// @return true if the proof is valid, else false\\n function verifyHash256Merkle(\\n bytes32 _leaf,\\n bytes memory _tree,\\n bytes32 _root,\\n uint _index\\n ) internal view returns (bool) {\\n // Not an even number of hashes\\n if (_tree.length % 32 != 0) {\\n return false;\\n }\\n\\n // Should never occur\\n if (_tree.length == 0) {\\n return false;\\n }\\n\\n uint _idx = _index;\\n bytes32 _current = _leaf;\\n\\n // i moves in increments of 32\\n for (uint i = 0; i < _tree.length; i += 32) {\\n if (_idx % 2 == 1) {\\n _current = _hash256MerkleStep(_tree.slice32(i), _current);\\n } else {\\n _current = _hash256MerkleStep(_current, _tree.slice32(i));\\n }\\n _idx = _idx >> 1;\\n }\\n return _current == _root;\\n }\\n\\n /*\\n NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72\\n NB: We get a full-bitlength target from this. For comparison with\\n header-encoded targets we need to mask it with the header target\\n e.g. (full & truncated) == truncated\\n */\\n /// @notice performs the bitcoin difficulty retarget\\n /// @dev implements the Bitcoin algorithm precisely\\n /// @param _previousTarget the target of the previous period\\n /// @param _firstTimestamp the timestamp of the first block in the difficulty period\\n /// @param _secondTimestamp the timestamp of the last block in the difficulty period\\n /// @return the new period's target threshold\\n function retargetAlgorithm(\\n uint256 _previousTarget,\\n uint256 _firstTimestamp,\\n uint256 _secondTimestamp\\n ) internal pure returns (uint256) {\\n uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);\\n\\n // Normalize ratio to factor of 4 if very long or very short\\n if (_elapsedTime < RETARGET_PERIOD.div(4)) {\\n _elapsedTime = RETARGET_PERIOD.div(4);\\n }\\n if (_elapsedTime > RETARGET_PERIOD.mul(4)) {\\n _elapsedTime = RETARGET_PERIOD.mul(4);\\n }\\n\\n /*\\n NB: high targets e.g. ffff0020 can cause overflows here\\n so we divide it by 256**2, then multiply by 256**2 later\\n we know the target is evenly divisible by 256**2, so this isn't an issue\\n */\\n\\n uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);\\n return _adjusted.div(RETARGET_PERIOD).mul(65536);\\n }\\n}\\n\",\"keccak256\":\"0x439eaa97e9239705f3d31e8d39dccbad32311f1f119e295d53c65e0ae3c5a5fc\"},\"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\":{\"content\":\"pragma solidity ^0.8.4;\\n\\n/*\\n\\nhttps://github.com/GNSPS/solidity-bytes-utils/\\n\\nThis is free and unencumbered software released into the public domain.\\n\\nAnyone is free to copy, modify, publish, use, compile, sell, or\\ndistribute this software, either in source code form or as a compiled\\nbinary, for any purpose, commercial or non-commercial, and by any\\nmeans.\\n\\nIn jurisdictions that recognize copyright laws, the author or authors\\nof this software dedicate any and all copyright interest in the\\nsoftware to the public domain. We make this dedication for the benefit\\nof the public at large and to the detriment of our heirs and\\nsuccessors. We intend this dedication to be an overt act of\\nrelinquishment in perpetuity of all present and future rights to this\\nsoftware under copyright law.\\n\\nTHE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND,\\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\\nOTHER DEALINGS IN THE SOFTWARE.\\n\\nFor more information, please refer to \\n*/\\n\\n\\n/** @title BytesLib **/\\n/** @author https://github.com/GNSPS **/\\n\\nlibrary BytesLib {\\n function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {\\n bytes memory tempBytes;\\n\\n assembly {\\n // Get a location of some free memory and store it in tempBytes as\\n // Solidity does for memory variables.\\n tempBytes := mload(0x40)\\n\\n // Store the length of the first bytes array at the beginning of\\n // the memory for tempBytes.\\n let length := mload(_preBytes)\\n mstore(tempBytes, length)\\n\\n // Maintain a memory counter for the current write location in the\\n // temp bytes array by adding the 32 bytes for the array length to\\n // the starting location.\\n let mc := add(tempBytes, 0x20)\\n // Stop copying when the memory counter reaches the length of the\\n // first bytes array.\\n let end := add(mc, length)\\n\\n for {\\n // Initialize a copy counter to the start of the _preBytes data,\\n // 32 bytes into its memory.\\n let cc := add(_preBytes, 0x20)\\n } lt(mc, end) {\\n // Increase both counters by 32 bytes each iteration.\\n mc := add(mc, 0x20)\\n cc := add(cc, 0x20)\\n } {\\n // Write the _preBytes data into the tempBytes memory 32 bytes\\n // at a time.\\n mstore(mc, mload(cc))\\n }\\n\\n // Add the length of _postBytes to the current length of tempBytes\\n // and store it as the new length in the first 32 bytes of the\\n // tempBytes memory.\\n length := mload(_postBytes)\\n mstore(tempBytes, add(length, mload(tempBytes)))\\n\\n // Move the memory counter back from a multiple of 0x20 to the\\n // actual end of the _preBytes data.\\n mc := end\\n // Stop copying when the memory counter reaches the new combined\\n // length of the arrays.\\n end := add(mc, length)\\n\\n for {\\n let cc := add(_postBytes, 0x20)\\n } lt(mc, end) {\\n mc := add(mc, 0x20)\\n cc := add(cc, 0x20)\\n } {\\n mstore(mc, mload(cc))\\n }\\n\\n // Update the free-memory pointer by padding our last write location\\n // to 32 bytes: add 31 bytes to the end of tempBytes to move to the\\n // next 32 byte block, then round down to the nearest multiple of\\n // 32. If the sum of the length of the two arrays is zero then add\\n // one before rounding down to leave a blank 32 bytes (the length block with 0).\\n mstore(0x40, and(\\n add(add(end, iszero(add(length, mload(_preBytes)))), 31),\\n not(31) // Round down to the nearest 32 bytes.\\n ))\\n }\\n\\n return tempBytes;\\n }\\n\\n function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {\\n assembly {\\n // Read the first 32 bytes of _preBytes storage, which is the length\\n // of the array. (We don't need to use the offset into the slot\\n // because arrays use the entire slot.)\\n let fslot := sload(_preBytes.slot)\\n // Arrays of 31 bytes or less have an even value in their slot,\\n // while longer arrays have an odd value. The actual length is\\n // the slot divided by two for odd values, and the lowest order\\n // byte divided by two for even values.\\n // If the slot is even, bitwise and the slot with 255 and divide by\\n // two to get the length. If the slot is odd, bitwise and the slot\\n // with -1 and divide by two.\\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\\n let mlength := mload(_postBytes)\\n let newlength := add(slength, mlength)\\n // slength can contain both the length and contents of the array\\n // if length < 32 bytes so let's prepare for that\\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\\n switch add(lt(slength, 32), lt(newlength, 32))\\n case 2 {\\n // Since the new array still fits in the slot, we just need to\\n // update the contents of the slot.\\n // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length\\n sstore(\\n _preBytes.slot,\\n // all the modifications to the slot are inside this\\n // next block\\n add(\\n // we can just add to the slot contents because the\\n // bytes we want to change are the LSBs\\n fslot,\\n add(\\n mul(\\n div(\\n // load the bytes from memory\\n mload(add(_postBytes, 0x20)),\\n // zero all bytes to the right\\n exp(0x100, sub(32, mlength))\\n ),\\n // and now shift left the number of bytes to\\n // leave space for the length in the slot\\n exp(0x100, sub(32, newlength))\\n ),\\n // increase length by the double of the memory\\n // bytes length\\n mul(mlength, 2)\\n )\\n )\\n )\\n }\\n case 1 {\\n // The stored value fits in the slot, but the combined value\\n // will exceed it.\\n // get the keccak hash to get the contents of the array\\n mstore(0x0, _preBytes.slot)\\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\\n\\n // save new length\\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\\n\\n // The contents of the _postBytes array start 32 bytes into\\n // the structure. Our first read should obtain the `submod`\\n // bytes that can fit into the unused space in the last word\\n // of the stored array. To get this, we read 32 bytes starting\\n // from `submod`, so the data we read overlaps with the array\\n // contents by `submod` bytes. Masking the lowest-order\\n // `submod` bytes allows us to add that value directly to the\\n // stored value.\\n\\n let submod := sub(32, slength)\\n let mc := add(_postBytes, submod)\\n let end := add(_postBytes, mlength)\\n let mask := sub(exp(0x100, submod), 1)\\n\\n sstore(\\n sc,\\n add(\\n and(\\n fslot,\\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00\\n ),\\n and(mload(mc), mask)\\n )\\n )\\n\\n for {\\n mc := add(mc, 0x20)\\n sc := add(sc, 1)\\n } lt(mc, end) {\\n sc := add(sc, 1)\\n mc := add(mc, 0x20)\\n } {\\n sstore(sc, mload(mc))\\n }\\n\\n mask := exp(0x100, sub(mc, end))\\n\\n sstore(sc, mul(div(mload(mc), mask), mask))\\n }\\n default {\\n // get the keccak hash to get the contents of the array\\n mstore(0x0, _preBytes.slot)\\n // Start copying to the last used word of the stored array.\\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\\n\\n // save new length\\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\\n\\n // Copy over the first `submod` bytes of the new data as in\\n // case 1 above.\\n let slengthmod := mod(slength, 32)\\n let mlengthmod := mod(mlength, 32)\\n let submod := sub(32, slengthmod)\\n let mc := add(_postBytes, submod)\\n let end := add(_postBytes, mlength)\\n let mask := sub(exp(0x100, submod), 1)\\n\\n sstore(sc, add(sload(sc), and(mload(mc), mask)))\\n\\n for {\\n sc := add(sc, 1)\\n mc := add(mc, 0x20)\\n } lt(mc, end) {\\n sc := add(sc, 1)\\n mc := add(mc, 0x20)\\n } {\\n sstore(sc, mload(mc))\\n }\\n\\n mask := exp(0x100, sub(mc, end))\\n\\n sstore(sc, mul(div(mload(mc), mask), mask))\\n }\\n }\\n }\\n\\n function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) {\\n if (_length == 0) {\\n return hex\\\"\\\";\\n }\\n uint _end = _start + _length;\\n require(_end > _start && _bytes.length >= _end, \\\"Slice out of bounds\\\");\\n\\n assembly {\\n // Alloc bytes array with additional 32 bytes afterspace and assign it's size\\n res := mload(0x40)\\n mstore(0x40, add(add(res, 64), _length))\\n mstore(res, _length)\\n\\n // Compute distance between source and destination pointers\\n let diff := sub(res, add(_bytes, _start))\\n\\n for {\\n let src := add(add(_bytes, 32), _start)\\n let end := add(src, _length)\\n } lt(src, end) {\\n src := add(src, 32)\\n } {\\n mstore(add(src, diff), mload(src))\\n }\\n }\\n }\\n\\n /// @notice Take a slice of the byte array, overwriting the destination.\\n /// The length of the slice will equal the length of the destination array.\\n /// @dev Make sure the destination array has afterspace if required.\\n /// @param _bytes The source array\\n /// @param _dest The destination array.\\n /// @param _start The location to start in the source array.\\n function sliceInPlace(\\n bytes memory _bytes,\\n bytes memory _dest,\\n uint _start\\n ) internal pure {\\n uint _length = _dest.length;\\n uint _end = _start + _length;\\n require(_end > _start && _bytes.length >= _end, \\\"Slice out of bounds\\\");\\n\\n assembly {\\n for {\\n let src := add(add(_bytes, 32), _start)\\n let res := add(_dest, 32)\\n let end := add(src, _length)\\n } lt(src, end) {\\n src := add(src, 32)\\n res := add(res, 32)\\n } {\\n mstore(res, mload(src))\\n }\\n }\\n }\\n\\n // Static slice functions, no bounds checking\\n /// @notice take a 32-byte slice from the specified position\\n function slice32(bytes memory _bytes, uint _start) internal pure returns (bytes32 res) {\\n assembly {\\n res := mload(add(add(_bytes, 32), _start))\\n }\\n }\\n\\n /// @notice take a 20-byte slice from the specified position\\n function slice20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {\\n return bytes20(slice32(_bytes, _start));\\n }\\n\\n /// @notice take a 8-byte slice from the specified position\\n function slice8(bytes memory _bytes, uint _start) internal pure returns (bytes8) {\\n return bytes8(slice32(_bytes, _start));\\n }\\n\\n /// @notice take a 4-byte slice from the specified position\\n function slice4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {\\n return bytes4(slice32(_bytes, _start));\\n }\\n\\n /// @notice take a 3-byte slice from the specified position\\n function slice3(bytes memory _bytes, uint _start) internal pure returns (bytes3) {\\n return bytes3(slice32(_bytes, _start));\\n }\\n\\n /// @notice take a 2-byte slice from the specified position\\n function slice2(bytes memory _bytes, uint _start) internal pure returns (bytes2) {\\n return bytes2(slice32(_bytes, _start));\\n }\\n\\n function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {\\n uint _totalLen = _start + 20;\\n require(_totalLen > _start && _bytes.length >= _totalLen, \\\"Address conversion out of bounds.\\\");\\n address tempAddress;\\n\\n assembly {\\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\\n }\\n\\n return tempAddress;\\n }\\n\\n function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {\\n uint _totalLen = _start + 32;\\n require(_totalLen > _start && _bytes.length >= _totalLen, \\\"Uint conversion out of bounds.\\\");\\n uint256 tempUint;\\n\\n assembly {\\n tempUint := mload(add(add(_bytes, 0x20), _start))\\n }\\n\\n return tempUint;\\n }\\n\\n function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {\\n bool success = true;\\n\\n assembly {\\n let length := mload(_preBytes)\\n\\n // if lengths don't match the arrays are not equal\\n switch eq(length, mload(_postBytes))\\n case 1 {\\n // cb is a circuit breaker in the for loop since there's\\n // no said feature for inline assembly loops\\n // cb = 1 - don't breaker\\n // cb = 0 - break\\n let cb := 1\\n\\n let mc := add(_preBytes, 0x20)\\n let end := add(mc, length)\\n\\n for {\\n let cc := add(_postBytes, 0x20)\\n // the next line is the loop condition:\\n // while(uint(mc < end) + cb == 2)\\n } eq(add(lt(mc, end), cb), 2) {\\n mc := add(mc, 0x20)\\n cc := add(cc, 0x20)\\n } {\\n // if any of these checks fails then arrays are not equal\\n if iszero(eq(mload(mc), mload(cc))) {\\n // unsuccess:\\n success := 0\\n cb := 0\\n }\\n }\\n }\\n default {\\n // unsuccess:\\n success := 0\\n }\\n }\\n\\n return success;\\n }\\n\\n function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {\\n bool success = true;\\n\\n assembly {\\n // we know _preBytes_offset is 0\\n let fslot := sload(_preBytes.slot)\\n // Decode the length of the stored array like in concatStorage().\\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\\n let mlength := mload(_postBytes)\\n\\n // if lengths don't match the arrays are not equal\\n switch eq(slength, mlength)\\n case 1 {\\n // slength can contain both the length and contents of the array\\n // if length < 32 bytes so let's prepare for that\\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\\n if iszero(iszero(slength)) {\\n switch lt(slength, 32)\\n case 1 {\\n // blank the last byte which is the length\\n fslot := mul(div(fslot, 0x100), 0x100)\\n\\n if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {\\n // unsuccess:\\n success := 0\\n }\\n }\\n default {\\n // cb is a circuit breaker in the for loop since there's\\n // no said feature for inline assembly loops\\n // cb = 1 - don't breaker\\n // cb = 0 - break\\n let cb := 1\\n\\n // get the keccak hash to get the contents of the array\\n mstore(0x0, _preBytes.slot)\\n let sc := keccak256(0x0, 0x20)\\n\\n let mc := add(_postBytes, 0x20)\\n let end := add(mc, mlength)\\n\\n // the next line is the loop condition:\\n // while(uint(mc < end) + cb == 2)\\n for {} eq(add(lt(mc, end), cb), 2) {\\n sc := add(sc, 1)\\n mc := add(mc, 0x20)\\n } {\\n if iszero(eq(sload(sc), mload(mc))) {\\n // unsuccess:\\n success := 0\\n cb := 0\\n }\\n }\\n }\\n }\\n }\\n default {\\n // unsuccess:\\n success := 0\\n }\\n }\\n\\n return success;\\n }\\n\\n function toBytes32(bytes memory _source) pure internal returns (bytes32 result) {\\n if (_source.length == 0) {\\n return 0x0;\\n }\\n\\n assembly {\\n result := mload(add(_source, 32))\\n }\\n }\\n\\n function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) {\\n uint _end = _start + _length;\\n require(_end > _start && _bytes.length >= _end, \\\"Slice out of bounds\\\");\\n\\n assembly {\\n result := keccak256(add(add(_bytes, 32), _start), _length)\\n }\\n }\\n}\\n\",\"keccak256\":\"0x43e0f3b3b23c861bd031588bf410dfdd02e2af17941a89aa38d70e534e0380d1\"},\"@keep-network/bitcoin-spv-sol/contracts/SafeMath.sol\":{\"content\":\"pragma solidity ^0.8.4;\\n\\n/*\\nThe MIT License (MIT)\\n\\nCopyright (c) 2016 Smart Contract Solutions, Inc.\\n\\nPermission is hereby granted, free of charge, to any person obtaining\\na copy of this software and associated documentation files (the\\n\\\"Software\\\"), to deal in the Software without restriction, including\\nwithout limitation the rights to use, copy, modify, merge, publish,\\ndistribute, sublicense, and/or sell copies of the Software, and to\\npermit persons to whom the Software is furnished to do so, subject to\\nthe following conditions:\\n\\nThe above copyright notice and this permission notice shall be included\\nin all copies or substantial portions of the Software.\\n\\nTHE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\\n*/\\n\\n\\n/**\\n * @title SafeMath\\n * @dev Math operations with safety checks that throw on error\\n */\\nlibrary SafeMath {\\n\\n /**\\n * @dev Multiplies two numbers, throws on overflow.\\n */\\n function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\\n // Gas optimization: this is cheaper than asserting 'a' not being zero, but the\\n // benefit is lost if 'b' is also tested.\\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\\n if (_a == 0) {\\n return 0;\\n }\\n\\n c = _a * _b;\\n require(c / _a == _b, \\\"Overflow during multiplication.\\\");\\n return c;\\n }\\n\\n /**\\n * @dev Integer division of two numbers, truncating the quotient.\\n */\\n function div(uint256 _a, uint256 _b) internal pure returns (uint256) {\\n // assert(_b > 0); // Solidity automatically throws when dividing by 0\\n // uint256 c = _a / _b;\\n // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold\\n return _a / _b;\\n }\\n\\n /**\\n * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).\\n */\\n function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {\\n require(_b <= _a, \\\"Underflow during subtraction.\\\");\\n return _a - _b;\\n }\\n\\n /**\\n * @dev Adds two numbers, throws on overflow.\\n */\\n function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\\n c = _a + _b;\\n require(c >= _a, \\\"Overflow during addition.\\\");\\n return c;\\n }\\n}\\n\",\"keccak256\":\"0x35930d982394c7ffde439b82e5e696c5b21a6f09699d44861dfe409ef64084a3\"},\"@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\n\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n\\npragma solidity ^0.8.0;\\n\\nimport {BTCUtils} from \\\"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\\\";\\n\\nimport \\\"./IBridge.sol\\\";\\nimport \\\"./ITBTCVault.sol\\\";\\n\\n/// @title Abstract AbstractTBTCDepositor contract.\\n/// @notice This abstract contract is meant to facilitate integration of protocols\\n/// aiming to use tBTC as an underlying Bitcoin bridge.\\n///\\n/// Such an integrator is supposed to:\\n/// - Create a child contract inheriting from this abstract contract\\n/// - Call the `__AbstractTBTCDepositor_initialize` initializer function\\n/// - Use the `_initializeDeposit` and `_finalizeDeposit` as part of their\\n/// business logic in order to initialize and finalize deposits.\\n///\\n/// @dev Example usage:\\n/// ```\\n/// // Example upgradeable integrator contract.\\n/// contract ExampleTBTCIntegrator is AbstractTBTCDepositor, Initializable {\\n/// /// @custom:oz-upgrades-unsafe-allow constructor\\n/// constructor() {\\n/// // Prevents the contract from being initialized again.\\n/// _disableInitializers();\\n/// }\\n///\\n/// function initialize(\\n/// address _bridge,\\n/// address _tbtcVault\\n/// ) external initializer {\\n/// __AbstractTBTCDepositor_initialize(_bridge, _tbtcVault);\\n/// }\\n///\\n/// function startProcess(\\n/// IBridgeTypes.BitcoinTxInfo calldata fundingTx,\\n/// IBridgeTypes.DepositRevealInfo calldata reveal\\n/// ) external {\\n/// // Embed necessary context as extra data.\\n/// bytes32 extraData = ...;\\n///\\n/// uint256 depositKey = _initializeDeposit(\\n/// fundingTx,\\n/// reveal,\\n/// extraData\\n/// );\\n///\\n/// // Use the depositKey to track the process.\\n/// }\\n///\\n/// function finalizeProcess(uint256 depositKey) external {\\n/// // Ensure the function cannot be called for the same deposit\\n/// // twice.\\n///\\n/// (\\n/// uint256 initialDepositAmount,\\n/// uint256 tbtcAmount,\\n/// bytes32 extraData\\n/// ) = _finalizeDeposit(depositKey);\\n///\\n/// // Do something with the minted TBTC using context\\n/// // embedded in the extraData.\\n/// }\\n/// }\\nabstract contract AbstractTBTCDepositor {\\n using BTCUtils for bytes;\\n\\n /// @notice Multiplier to convert satoshi to TBTC token units.\\n uint256 public constant SATOSHI_MULTIPLIER = 10**10;\\n\\n /// @notice Bridge contract address.\\n IBridge public bridge;\\n /// @notice TBTCVault contract address.\\n ITBTCVault public tbtcVault;\\n\\n // Reserved storage space that allows adding more variables without affecting\\n // the storage layout of the child contracts. The convention from OpenZeppelin\\n // suggests the storage space should add up to 50 slots. If more variables are\\n // added in the upcoming versions one need to reduce the array size accordingly.\\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n // slither-disable-next-line unused-state\\n uint256[47] private __gap;\\n\\n event DepositInitialized(uint256 indexed depositKey, uint32 initializedAt);\\n\\n event DepositFinalized(\\n uint256 indexed depositKey,\\n uint256 tbtcAmount,\\n uint32 finalizedAt\\n );\\n\\n /// @notice Initializes the contract. MUST BE CALLED from the child\\n /// contract initializer.\\n // slither-disable-next-line dead-code\\n function __AbstractTBTCDepositor_initialize(\\n address _bridge,\\n address _tbtcVault\\n ) internal {\\n require(\\n address(bridge) == address(0) && address(tbtcVault) == address(0),\\n \\\"AbstractTBTCDepositor already initialized\\\"\\n );\\n\\n require(_bridge != address(0), \\\"Bridge address cannot be zero\\\");\\n require(_tbtcVault != address(0), \\\"TBTCVault address cannot be zero\\\");\\n\\n bridge = IBridge(_bridge);\\n tbtcVault = ITBTCVault(_tbtcVault);\\n }\\n\\n /// @notice Initializes a deposit by revealing it to the Bridge.\\n /// @param fundingTx Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.\\n /// @param reveal Deposit reveal data, see `IBridgeTypes.DepositRevealInfo` struct.\\n /// @param extraData 32-byte deposit extra data.\\n /// @return depositKey Deposit key computed as\\n /// `keccak256(fundingTxHash | reveal.fundingOutputIndex)`. This\\n /// key can be used to refer to the deposit in the Bridge and\\n /// TBTCVault contracts.\\n /// @dev Requirements:\\n /// - The revealed vault address must match the TBTCVault address,\\n /// - All requirements from {Bridge#revealDepositWithExtraData}\\n /// function must be met.\\n /// @dev This function doesn't validate if a deposit has been initialized before,\\n /// as the Bridge won't allow the same deposit to be revealed twice.\\n // slither-disable-next-line dead-code\\n function _initializeDeposit(\\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\\n IBridgeTypes.DepositRevealInfo calldata reveal,\\n bytes32 extraData\\n ) internal returns (uint256) {\\n require(reveal.vault == address(tbtcVault), \\\"Vault address mismatch\\\");\\n\\n uint256 depositKey = _calculateDepositKey(\\n _calculateBitcoinTxHash(fundingTx),\\n reveal.fundingOutputIndex\\n );\\n\\n emit DepositInitialized(\\n depositKey,\\n /* solhint-disable-next-line not-rely-on-time */\\n uint32(block.timestamp)\\n );\\n\\n // The Bridge does not allow to reveal the same deposit twice and\\n // revealed deposits stay there forever. The transaction will revert\\n // if the deposit has already been revealed so, there is no need to do\\n // an explicit check here.\\n bridge.revealDepositWithExtraData(fundingTx, reveal, extraData);\\n\\n return depositKey;\\n }\\n\\n /// @notice Finalizes a deposit by calculating the amount of TBTC minted\\n /// for the deposit.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @return initialDepositAmount Amount of funding transaction deposit. In\\n /// TBTC token decimals precision.\\n /// @return tbtcAmount Approximate amount of TBTC minted for the deposit. In\\n /// TBTC token decimals precision.\\n /// @return extraData 32-byte deposit extra data.\\n /// @dev Requirements:\\n /// - The deposit must be initialized but not finalized\\n /// (in the context of this contract) yet.\\n /// - The deposit must be finalized on the Bridge side. That means the\\n /// deposit must be either swept or optimistically minted.\\n /// @dev THIS FUNCTION DOESN'T VALIDATE IF A DEPOSIT HAS BEEN FINALIZED BEFORE,\\n /// IT IS A RESPONSIBILITY OF THE IMPLEMENTING CONTRACT TO ENSURE THIS\\n /// FUNCTION WON'T BE CALLED TWICE FOR THE SAME DEPOSIT.\\n /// @dev IMPORTANT NOTE: The tbtcAmount returned by this function is an\\n /// approximation. See documentation of the `calculateTbtcAmount`\\n /// responsible for calculating this value for more details.\\n // slither-disable-next-line dead-code\\n function _finalizeDeposit(uint256 depositKey)\\n internal\\n returns (\\n uint256 initialDepositAmount,\\n uint256 tbtcAmount,\\n bytes32 extraData\\n )\\n {\\n IBridgeTypes.DepositRequest memory deposit = bridge.deposits(\\n depositKey\\n );\\n require(deposit.revealedAt != 0, \\\"Deposit not initialized\\\");\\n\\n (, uint64 finalizedAt) = tbtcVault.optimisticMintingRequests(\\n depositKey\\n );\\n\\n require(\\n deposit.sweptAt != 0 || finalizedAt != 0,\\n \\\"Deposit not finalized by the bridge\\\"\\n );\\n\\n initialDepositAmount = deposit.amount * SATOSHI_MULTIPLIER;\\n\\n tbtcAmount = _calculateTbtcAmount(deposit.amount, deposit.treasuryFee);\\n\\n // slither-disable-next-line reentrancy-events\\n emit DepositFinalized(\\n depositKey,\\n tbtcAmount,\\n /* solhint-disable-next-line not-rely-on-time */\\n uint32(block.timestamp)\\n );\\n\\n extraData = deposit.extraData;\\n }\\n\\n /// @notice Calculates the amount of TBTC minted for the deposit.\\n /// @param depositAmountSat Deposit amount in satoshi (1e8 precision).\\n /// This is the actual amount deposited by the deposit creator, i.e.\\n /// the gross amount the Bridge's fees are cut from.\\n /// @param depositTreasuryFeeSat Deposit treasury fee in satoshi (1e8 precision).\\n /// This is an accurate value of the treasury fee that was actually\\n /// cut upon minting.\\n /// @return tbtcAmount Approximate amount of TBTC minted for the deposit.\\n /// @dev IMPORTANT NOTE: The tbtcAmount returned by this function may\\n /// not correspond to the actual amount of TBTC minted for the deposit.\\n /// Although the treasury fee cut upon minting is known precisely,\\n /// this is not the case for the optimistic minting fee and the Bitcoin\\n /// transaction fee. To overcome that problem, this function just takes\\n /// the current maximum allowed values of both fees, at the moment of deposit\\n /// finalization. For the great majority of the deposits, such an\\n /// algorithm will return a tbtcAmount slightly lesser than the\\n /// actual amount of TBTC minted for the deposit. This will cause\\n /// some TBTC to be left in the contract and ensure there is enough\\n /// liquidity to finalize the deposit. However, in some rare cases,\\n /// where the actual values of those fees change between the deposit\\n /// minting and finalization, the tbtcAmount returned by this function\\n /// may be greater than the actual amount of TBTC minted for the deposit.\\n /// If this happens and the reserve coming from previous deposits\\n /// leftovers does not provide enough liquidity, the deposit will have\\n /// to wait for finalization until the reserve is refilled by subsequent\\n /// deposits or a manual top-up. The integrator is responsible for\\n /// handling such cases.\\n // slither-disable-next-line dead-code\\n function _calculateTbtcAmount(\\n uint64 depositAmountSat,\\n uint64 depositTreasuryFeeSat\\n ) internal view virtual returns (uint256) {\\n // Both deposit amount and treasury fee are in the 1e8 satoshi precision.\\n // We need to convert them to the 1e18 TBTC precision.\\n uint256 amountSubTreasury = (depositAmountSat - depositTreasuryFeeSat) *\\n SATOSHI_MULTIPLIER;\\n\\n uint256 omFeeDivisor = tbtcVault.optimisticMintingFeeDivisor();\\n uint256 omFee = omFeeDivisor > 0\\n ? (amountSubTreasury / omFeeDivisor)\\n : 0;\\n\\n // The deposit transaction max fee is in the 1e8 satoshi precision.\\n // We need to convert them to the 1e18 TBTC precision.\\n (, , uint64 depositTxMaxFee, ) = bridge.depositParameters();\\n uint256 txMaxFee = depositTxMaxFee * SATOSHI_MULTIPLIER;\\n\\n return amountSubTreasury - omFee - txMaxFee;\\n }\\n\\n /// @notice Calculates the deposit key for the given funding transaction\\n /// hash and funding output index.\\n /// @param fundingTxHash Funding transaction hash.\\n /// @param fundingOutputIndex Funding output index.\\n /// @return depositKey Deposit key computed as\\n /// `keccak256(fundingTxHash | reveal.fundingOutputIndex)`. This\\n /// key can be used to refer to the deposit in the Bridge and\\n /// TBTCVault contracts.\\n // slither-disable-next-line dead-code\\n function _calculateDepositKey(\\n bytes32 fundingTxHash,\\n uint32 fundingOutputIndex\\n ) internal pure returns (uint256) {\\n return\\n uint256(\\n keccak256(abi.encodePacked(fundingTxHash, fundingOutputIndex))\\n );\\n }\\n\\n /// @notice Calculates the Bitcoin transaction hash for the given Bitcoin\\n /// transaction data.\\n /// @param txInfo Bitcoin transaction data, see `IBridgeTypes.BitcoinTxInfo` struct.\\n /// @return txHash Bitcoin transaction hash.\\n // slither-disable-next-line dead-code\\n function _calculateBitcoinTxHash(IBridgeTypes.BitcoinTxInfo calldata txInfo)\\n internal\\n view\\n returns (bytes32)\\n {\\n return\\n abi\\n .encodePacked(\\n txInfo.version,\\n txInfo.inputVector,\\n txInfo.outputVector,\\n txInfo.locktime\\n )\\n .hash256View();\\n }\\n}\\n\",\"keccak256\":\"0x0cfd2215c106fc17c8166a31839243ad1575806401de60f80d0a4857a2a60078\",\"license\":\"GPL-3.0-only\"},\"@keep-network/tbtc-v2/contracts/integrator/IBridge.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\n\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n\\npragma solidity ^0.8.0;\\n\\n/// @notice Namespace which groups all types relevant to the IBridge interface.\\n/// @dev This is a mirror of the real types used in the Bridge contract.\\n/// This way, the `integrator` subpackage does not need to import\\n/// anything from the `bridge` subpackage and explicitly depend on it.\\n/// This simplifies the dependency graph for integrators.\\nlibrary IBridgeTypes {\\n /// @dev See bridge/BitcoinTx.sol#Info\\n struct BitcoinTxInfo {\\n bytes4 version;\\n bytes inputVector;\\n bytes outputVector;\\n bytes4 locktime;\\n }\\n\\n /// @dev See bridge/Deposit.sol#DepositRevealInfo\\n struct DepositRevealInfo {\\n uint32 fundingOutputIndex;\\n bytes8 blindingFactor;\\n bytes20 walletPubKeyHash;\\n bytes20 refundPubKeyHash;\\n bytes4 refundLocktime;\\n address vault;\\n }\\n\\n /// @dev See bridge/Deposit.sol#DepositRequest\\n struct DepositRequest {\\n address depositor;\\n uint64 amount;\\n uint32 revealedAt;\\n address vault;\\n uint64 treasuryFee;\\n uint32 sweptAt;\\n bytes32 extraData;\\n }\\n}\\n\\n/// @notice Interface of the Bridge contract.\\n/// @dev See bridge/Bridge.sol\\ninterface IBridge {\\n /// @dev See {Bridge#revealDepositWithExtraData}\\n function revealDepositWithExtraData(\\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\\n IBridgeTypes.DepositRevealInfo calldata reveal,\\n bytes32 extraData\\n ) external;\\n\\n /// @dev See {Bridge#deposits}\\n function deposits(uint256 depositKey)\\n external\\n view\\n returns (IBridgeTypes.DepositRequest memory);\\n\\n /// @dev See {Bridge#depositParameters}\\n function depositParameters()\\n external\\n view\\n returns (\\n uint64 depositDustThreshold,\\n uint64 depositTreasuryFeeDivisor,\\n uint64 depositTxMaxFee,\\n uint32 depositRevealAheadPeriod\\n );\\n}\\n\",\"keccak256\":\"0x4e598d96404a19609f511f10503e80f457602ad694d081df739571f67f6e0c4e\",\"license\":\"GPL-3.0-only\"},\"@keep-network/tbtc-v2/contracts/integrator/ITBTCVault.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\n\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n\\npragma solidity ^0.8.0;\\n\\n/// @notice Interface of the TBTCVault contract.\\n/// @dev See vault/TBTCVault.sol\\ninterface ITBTCVault {\\n /// @dev See {TBTCVault#optimisticMintingRequests}\\n function optimisticMintingRequests(uint256 depositKey)\\n external\\n returns (uint64 requestedAt, uint64 finalizedAt);\\n\\n /// @dev See {TBTCVault#optimisticMintingFeeDivisor}\\n function optimisticMintingFeeDivisor() external view returns (uint32);\\n}\\n\",\"keccak256\":\"0xf259d64c1040e2cbc3d17653491e45c5c3da17f575dac1c175c63c8a5308908e\",\"license\":\"GPL-3.0-only\"},\"@openzeppelin/contracts/access/Ownable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {Context} from \\\"../utils/Context.sol\\\";\\n\\n/**\\n * @dev Contract module which provides a basic access control mechanism, where\\n * there is an account (an owner) that can be granted exclusive access to\\n * specific functions.\\n *\\n * The initial owner is set to the address provided by the deployer. This can\\n * later be changed with {transferOwnership}.\\n *\\n * This module is used through inheritance. It will make available the modifier\\n * `onlyOwner`, which can be applied to your functions to restrict their use to\\n * the owner.\\n */\\nabstract contract Ownable is Context {\\n address private _owner;\\n\\n /**\\n * @dev The caller account is not authorized to perform an operation.\\n */\\n error OwnableUnauthorizedAccount(address account);\\n\\n /**\\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\\n */\\n error OwnableInvalidOwner(address owner);\\n\\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\\n\\n /**\\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\\n */\\n constructor(address initialOwner) {\\n if (initialOwner == address(0)) {\\n revert OwnableInvalidOwner(address(0));\\n }\\n _transferOwnership(initialOwner);\\n }\\n\\n /**\\n * @dev Throws if called by any account other than the owner.\\n */\\n modifier onlyOwner() {\\n _checkOwner();\\n _;\\n }\\n\\n /**\\n * @dev Returns the address of the current owner.\\n */\\n function owner() public view virtual returns (address) {\\n return _owner;\\n }\\n\\n /**\\n * @dev Throws if the sender is not the owner.\\n */\\n function _checkOwner() internal view virtual {\\n if (owner() != _msgSender()) {\\n revert OwnableUnauthorizedAccount(_msgSender());\\n }\\n }\\n\\n /**\\n * @dev Leaves the contract without owner. It will not be possible to call\\n * `onlyOwner` functions. Can only be called by the current owner.\\n *\\n * NOTE: Renouncing ownership will leave the contract without an owner,\\n * thereby disabling any functionality that is only available to the owner.\\n */\\n function renounceOwnership() public virtual onlyOwner {\\n _transferOwnership(address(0));\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Can only be called by the current owner.\\n */\\n function transferOwnership(address newOwner) public virtual onlyOwner {\\n if (newOwner == address(0)) {\\n revert OwnableInvalidOwner(address(0));\\n }\\n _transferOwnership(newOwner);\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Internal function without access restriction.\\n */\\n function _transferOwnership(address newOwner) internal virtual {\\n address oldOwner = _owner;\\n _owner = newOwner;\\n emit OwnershipTransferred(oldOwner, newOwner);\\n }\\n}\\n\",\"keccak256\":\"0xff6d0bb2e285473e5311d9d3caacb525ae3538a80758c10649a4d61029b017bb\",\"license\":\"MIT\"},\"@openzeppelin/contracts/access/Ownable2Step.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {Ownable} from \\\"./Ownable.sol\\\";\\n\\n/**\\n * @dev Contract module which provides access control mechanism, where\\n * there is an account (an owner) that can be granted exclusive access to\\n * specific functions.\\n *\\n * The initial owner is specified at deployment time in the constructor for `Ownable`. This\\n * can later be changed with {transferOwnership} and {acceptOwnership}.\\n *\\n * This module is used through inheritance. It will make available all functions\\n * from parent (Ownable).\\n */\\nabstract contract Ownable2Step is Ownable {\\n address private _pendingOwner;\\n\\n event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\\n\\n /**\\n * @dev Returns the address of the pending owner.\\n */\\n function pendingOwner() public view virtual returns (address) {\\n return _pendingOwner;\\n }\\n\\n /**\\n * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\\n * Can only be called by the current owner.\\n */\\n function transferOwnership(address newOwner) public virtual override onlyOwner {\\n _pendingOwner = newOwner;\\n emit OwnershipTransferStarted(owner(), newOwner);\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\\n * Internal function without access restriction.\\n */\\n function _transferOwnership(address newOwner) internal virtual override {\\n delete _pendingOwner;\\n super._transferOwnership(newOwner);\\n }\\n\\n /**\\n * @dev The new owner accepts the ownership transfer.\\n */\\n function acceptOwnership() public virtual {\\n address sender = _msgSender();\\n if (pendingOwner() != sender) {\\n revert OwnableUnauthorizedAccount(sender);\\n }\\n _transferOwnership(sender);\\n }\\n}\\n\",\"keccak256\":\"0x5d3e5de9eadfa1f8a892eb2e95bbebd3e4b8c8ada5b76f104d383fea518fa688\",\"license\":\"MIT\"},\"@openzeppelin/contracts/interfaces/IERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../token/ERC20/IERC20.sol\\\";\\nimport {IERC20Metadata} from \\\"../token/ERC20/extensions/IERC20Metadata.sol\\\";\\n\\n/**\\n * @dev Interface of the ERC4626 \\\"Tokenized Vault Standard\\\", as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\\n */\\ninterface IERC4626 is IERC20, IERC20Metadata {\\n event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\\n\\n event Withdraw(\\n address indexed sender,\\n address indexed receiver,\\n address indexed owner,\\n uint256 assets,\\n uint256 shares\\n );\\n\\n /**\\n * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\\n *\\n * - MUST be an ERC-20 token contract.\\n * - MUST NOT revert.\\n */\\n function asset() external view returns (address assetTokenAddress);\\n\\n /**\\n * @dev Returns the total amount of the underlying asset that is \\u201cmanaged\\u201d by Vault.\\n *\\n * - SHOULD include any compounding that occurs from yield.\\n * - MUST be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT revert.\\n */\\n function totalAssets() external view returns (uint256 totalManagedAssets);\\n\\n /**\\n * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToShares(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\\n * through a deposit call.\\n *\\n * - MUST return a limited value if receiver is subject to some deposit limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\\n * - MUST NOT revert.\\n */\\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\\n * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\\n * in the same transaction.\\n * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\\n * deposit would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * deposit execution, and are accounted for during deposit.\\n * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\\n * - MUST return a limited value if receiver is subject to some mint limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\\n * - MUST NOT revert.\\n */\\n function maxMint(address receiver) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\\n * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\\n * same transaction.\\n * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\\n * would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by minting.\\n */\\n function previewMint(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\\n * execution, and are accounted for during mint.\\n * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\\n * Vault, through a withdraw call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\\n * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\\n * called\\n * in the same transaction.\\n * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\\n * the withdrawal would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * withdraw execution, and are accounted for during withdraw.\\n * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\\n * through a redeem call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxRedeem(address owner) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\\n * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\\n * same transaction.\\n * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\\n * redemption would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\\n */\\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * redeem execution, and are accounted for during redeem.\\n * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\\n}\\n\",\"keccak256\":\"0x207f64371bc0fcc5be86713aa5da109a870cc3a6da50e93b64ee881e369b593d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Standard ERC20 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.\\n */\\ninterface IERC20Errors {\\n /**\\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param balance Current balance for the interacting account.\\n * @param needed Minimum amount required to perform a transfer.\\n */\\n error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC20InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC20InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `spender`\\u2019s `allowance`. Used in transfers.\\n * @param spender Address that may be allowed to operate on tokens without being their owner.\\n * @param allowance Amount of tokens a `spender` is allowed to operate with.\\n * @param needed Minimum amount required to perform a transfer.\\n */\\n error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC20InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\\n * @param spender Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC20InvalidSpender(address spender);\\n}\\n\\n/**\\n * @dev Standard ERC721 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.\\n */\\ninterface IERC721Errors {\\n /**\\n * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.\\n * Used in balance queries.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC721InvalidOwner(address owner);\\n\\n /**\\n * @dev Indicates a `tokenId` whose `owner` is the zero address.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC721NonexistentToken(uint256 tokenId);\\n\\n /**\\n * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param tokenId Identifier number of a token.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC721InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC721InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `operator`\\u2019s approval. Used in transfers.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC721InsufficientApproval(address operator, uint256 tokenId);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC721InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC721InvalidOperator(address operator);\\n}\\n\\n/**\\n * @dev Standard ERC1155 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.\\n */\\ninterface IERC1155Errors {\\n /**\\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param balance Current balance for the interacting account.\\n * @param needed Minimum amount required to perform a transfer.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC1155InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC1155InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `operator`\\u2019s approval. Used in transfers.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC1155MissingApprovalForAll(address operator, address owner);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC1155InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC1155InvalidOperator(address operator);\\n\\n /**\\n * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\\n * Used in batch transfers.\\n * @param idsLength Length of the array of token identifiers\\n * @param valuesLength Length of the array of token amounts\\n */\\n error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\\n}\\n\",\"keccak256\":\"0x60c65f701957fdd6faea1acb0bb45825791d473693ed9ecb34726fdfaa849dd7\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/ERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"./IERC20.sol\\\";\\nimport {IERC20Metadata} from \\\"./extensions/IERC20Metadata.sol\\\";\\nimport {Context} from \\\"../../utils/Context.sol\\\";\\nimport {IERC20Errors} from \\\"../../interfaces/draft-IERC6093.sol\\\";\\n\\n/**\\n * @dev Implementation of the {IERC20} interface.\\n *\\n * This implementation is agnostic to the way tokens are created. This means\\n * that a supply mechanism has to be added in a derived contract using {_mint}.\\n *\\n * TIP: For a detailed writeup see our guide\\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\\n * to implement supply mechanisms].\\n *\\n * The default value of {decimals} is 18. To change this, you should override\\n * this function so it returns a different value.\\n *\\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\\n * instead returning `false` on failure. This behavior is nonetheless\\n * conventional and does not conflict with the expectations of ERC20\\n * applications.\\n *\\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\\n * This allows applications to reconstruct the allowance for all accounts just\\n * by listening to said events. Other implementations of the EIP may not emit\\n * these events, as it isn't required by the specification.\\n */\\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\\n mapping(address account => uint256) private _balances;\\n\\n mapping(address account => mapping(address spender => uint256)) private _allowances;\\n\\n uint256 private _totalSupply;\\n\\n string private _name;\\n string private _symbol;\\n\\n /**\\n * @dev Sets the values for {name} and {symbol}.\\n *\\n * All two of these values are immutable: they can only be set once during\\n * construction.\\n */\\n constructor(string memory name_, string memory symbol_) {\\n _name = name_;\\n _symbol = symbol_;\\n }\\n\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() public view virtual returns (string memory) {\\n return _name;\\n }\\n\\n /**\\n * @dev Returns the symbol of the token, usually a shorter version of the\\n * name.\\n */\\n function symbol() public view virtual returns (string memory) {\\n return _symbol;\\n }\\n\\n /**\\n * @dev Returns the number of decimals used to get its user representation.\\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\\n *\\n * Tokens usually opt for a value of 18, imitating the relationship between\\n * Ether and Wei. This is the default value returned by this function, unless\\n * it's overridden.\\n *\\n * NOTE: This information is only used for _display_ purposes: it in\\n * no way affects any of the arithmetic of the contract, including\\n * {IERC20-balanceOf} and {IERC20-transfer}.\\n */\\n function decimals() public view virtual returns (uint8) {\\n return 18;\\n }\\n\\n /**\\n * @dev See {IERC20-totalSupply}.\\n */\\n function totalSupply() public view virtual returns (uint256) {\\n return _totalSupply;\\n }\\n\\n /**\\n * @dev See {IERC20-balanceOf}.\\n */\\n function balanceOf(address account) public view virtual returns (uint256) {\\n return _balances[account];\\n }\\n\\n /**\\n * @dev See {IERC20-transfer}.\\n *\\n * Requirements:\\n *\\n * - `to` cannot be the zero address.\\n * - the caller must have a balance of at least `value`.\\n */\\n function transfer(address to, uint256 value) public virtual returns (bool) {\\n address owner = _msgSender();\\n _transfer(owner, to, value);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-allowance}.\\n */\\n function allowance(address owner, address spender) public view virtual returns (uint256) {\\n return _allowances[owner][spender];\\n }\\n\\n /**\\n * @dev See {IERC20-approve}.\\n *\\n * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\\n * `transferFrom`. This is semantically equivalent to an infinite approval.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n */\\n function approve(address spender, uint256 value) public virtual returns (bool) {\\n address owner = _msgSender();\\n _approve(owner, spender, value);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-transferFrom}.\\n *\\n * Emits an {Approval} event indicating the updated allowance. This is not\\n * required by the EIP. See the note at the beginning of {ERC20}.\\n *\\n * NOTE: Does not update the allowance if the current allowance\\n * is the maximum `uint256`.\\n *\\n * Requirements:\\n *\\n * - `from` and `to` cannot be the zero address.\\n * - `from` must have a balance of at least `value`.\\n * - the caller must have allowance for ``from``'s tokens of at least\\n * `value`.\\n */\\n function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\\n address spender = _msgSender();\\n _spendAllowance(from, spender, value);\\n _transfer(from, to, value);\\n return true;\\n }\\n\\n /**\\n * @dev Moves a `value` amount of tokens from `from` to `to`.\\n *\\n * This internal function is equivalent to {transfer}, and can be used to\\n * e.g. implement automatic token fees, slashing mechanisms, etc.\\n *\\n * Emits a {Transfer} event.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead.\\n */\\n function _transfer(address from, address to, uint256 value) internal {\\n if (from == address(0)) {\\n revert ERC20InvalidSender(address(0));\\n }\\n if (to == address(0)) {\\n revert ERC20InvalidReceiver(address(0));\\n }\\n _update(from, to, value);\\n }\\n\\n /**\\n * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\\n * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\\n * this function.\\n *\\n * Emits a {Transfer} event.\\n */\\n function _update(address from, address to, uint256 value) internal virtual {\\n if (from == address(0)) {\\n // Overflow check required: The rest of the code assumes that totalSupply never overflows\\n _totalSupply += value;\\n } else {\\n uint256 fromBalance = _balances[from];\\n if (fromBalance < value) {\\n revert ERC20InsufficientBalance(from, fromBalance, value);\\n }\\n unchecked {\\n // Overflow not possible: value <= fromBalance <= totalSupply.\\n _balances[from] = fromBalance - value;\\n }\\n }\\n\\n if (to == address(0)) {\\n unchecked {\\n // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\\n _totalSupply -= value;\\n }\\n } else {\\n unchecked {\\n // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\\n _balances[to] += value;\\n }\\n }\\n\\n emit Transfer(from, to, value);\\n }\\n\\n /**\\n * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\\n * Relies on the `_update` mechanism\\n *\\n * Emits a {Transfer} event with `from` set to the zero address.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead.\\n */\\n function _mint(address account, uint256 value) internal {\\n if (account == address(0)) {\\n revert ERC20InvalidReceiver(address(0));\\n }\\n _update(address(0), account, value);\\n }\\n\\n /**\\n * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\\n * Relies on the `_update` mechanism.\\n *\\n * Emits a {Transfer} event with `to` set to the zero address.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead\\n */\\n function _burn(address account, uint256 value) internal {\\n if (account == address(0)) {\\n revert ERC20InvalidSender(address(0));\\n }\\n _update(account, address(0), value);\\n }\\n\\n /**\\n * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\\n *\\n * This internal function is equivalent to `approve`, and can be used to\\n * e.g. set automatic allowances for certain subsystems, etc.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `owner` cannot be the zero address.\\n * - `spender` cannot be the zero address.\\n *\\n * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\\n */\\n function _approve(address owner, address spender, uint256 value) internal {\\n _approve(owner, spender, value, true);\\n }\\n\\n /**\\n * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\\n *\\n * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\\n * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\\n * `Approval` event during `transferFrom` operations.\\n *\\n * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\\n * true using the following override:\\n * ```\\n * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\\n * super._approve(owner, spender, value, true);\\n * }\\n * ```\\n *\\n * Requirements are the same as {_approve}.\\n */\\n function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\\n if (owner == address(0)) {\\n revert ERC20InvalidApprover(address(0));\\n }\\n if (spender == address(0)) {\\n revert ERC20InvalidSpender(address(0));\\n }\\n _allowances[owner][spender] = value;\\n if (emitEvent) {\\n emit Approval(owner, spender, value);\\n }\\n }\\n\\n /**\\n * @dev Updates `owner` s allowance for `spender` based on spent `value`.\\n *\\n * Does not update the allowance value in case of infinite allowance.\\n * Revert if not enough allowance is available.\\n *\\n * Does not emit an {Approval} event.\\n */\\n function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\\n uint256 currentAllowance = allowance(owner, spender);\\n if (currentAllowance != type(uint256).max) {\\n if (currentAllowance < value) {\\n revert ERC20InsufficientAllowance(spender, currentAllowance, value);\\n }\\n unchecked {\\n _approve(owner, spender, currentAllowance - value, false);\\n }\\n }\\n }\\n}\\n\",\"keccak256\":\"0xc3e1fa9d1987f8d349dfb4d6fe93bf2ca014b52ba335cfac30bfe71e357e6f80\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/IERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Interface of the ERC20 standard as defined in the EIP.\\n */\\ninterface IERC20 {\\n /**\\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\\n * another (`to`).\\n *\\n * Note that `value` may be zero.\\n */\\n event Transfer(address indexed from, address indexed to, uint256 value);\\n\\n /**\\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\\n * a call to {approve}. `value` is the new allowance.\\n */\\n event Approval(address indexed owner, address indexed spender, uint256 value);\\n\\n /**\\n * @dev Returns the value of tokens in existence.\\n */\\n function totalSupply() external view returns (uint256);\\n\\n /**\\n * @dev Returns the value of tokens owned by `account`.\\n */\\n function balanceOf(address account) external view returns (uint256);\\n\\n /**\\n * @dev Moves a `value` amount of tokens from the caller's account to `to`.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transfer(address to, uint256 value) external returns (bool);\\n\\n /**\\n * @dev Returns the remaining number of tokens that `spender` will be\\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\\n * zero by default.\\n *\\n * This value changes when {approve} or {transferFrom} are called.\\n */\\n function allowance(address owner, address spender) external view returns (uint256);\\n\\n /**\\n * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\\n * caller's tokens.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\\n * that someone may use both the old and the new allowance by unfortunate\\n * transaction ordering. One possible solution to mitigate this race\\n * condition is to first reduce the spender's allowance to 0 and set the\\n * desired value afterwards:\\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\\n *\\n * Emits an {Approval} event.\\n */\\n function approve(address spender, uint256 value) external returns (bool);\\n\\n /**\\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\\n * allowance mechanism. `value` is then deducted from the caller's\\n * allowance.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transferFrom(address from, address to, uint256 value) external returns (bool);\\n}\\n\",\"keccak256\":\"0xc6a8ff0ea489379b61faa647490411b80102578440ab9d84e9a957cc12164e70\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20, IERC20Metadata, ERC20} from \\\"../ERC20.sol\\\";\\nimport {SafeERC20} from \\\"../utils/SafeERC20.sol\\\";\\nimport {IERC4626} from \\\"../../../interfaces/IERC4626.sol\\\";\\nimport {Math} from \\\"../../../utils/math/Math.sol\\\";\\n\\n/**\\n * @dev Implementation of the ERC4626 \\\"Tokenized Vault Standard\\\" as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].\\n *\\n * This extension allows the minting and burning of \\\"shares\\\" (represented using the ERC20 inheritance) in exchange for\\n * underlying \\\"assets\\\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\\n * the ERC20 standard. Any additional extensions included along it would affect the \\\"shares\\\" token represented by this\\n * contract and not the \\\"assets\\\" token which is an independent contract.\\n *\\n * [CAUTION]\\n * ====\\n * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning\\n * with a \\\"donation\\\" to the vault that inflates the price of a share. This is variously known as a donation or inflation\\n * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial\\n * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may\\n * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by\\n * verifying the amount received is as expected, using a wrapper that performs these checks such as\\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\\n *\\n * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`\\n * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault\\n * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself\\n * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset\\n * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's\\n * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more\\n * expensive than it is profitable. More details about the underlying math can be found\\n * xref:erc4626.adoc#inflation-attack[here].\\n *\\n * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued\\n * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets\\n * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience\\n * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the\\n * `_convertToShares` and `_convertToAssets` functions.\\n *\\n * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].\\n * ====\\n */\\nabstract contract ERC4626 is ERC20, IERC4626 {\\n using Math for uint256;\\n\\n IERC20 private immutable _asset;\\n uint8 private immutable _underlyingDecimals;\\n\\n /**\\n * @dev Attempted to deposit more assets than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);\\n\\n /**\\n * @dev Attempted to mint more shares than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);\\n\\n /**\\n * @dev Attempted to withdraw more assets than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);\\n\\n /**\\n * @dev Attempted to redeem more shares than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);\\n\\n /**\\n * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).\\n */\\n constructor(IERC20 asset_) {\\n (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\\n _underlyingDecimals = success ? assetDecimals : 18;\\n _asset = asset_;\\n }\\n\\n /**\\n * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\\n */\\n function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {\\n (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(\\n abi.encodeCall(IERC20Metadata.decimals, ())\\n );\\n if (success && encodedDecimals.length >= 32) {\\n uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));\\n if (returnedDecimals <= type(uint8).max) {\\n return (true, uint8(returnedDecimals));\\n }\\n }\\n return (false, 0);\\n }\\n\\n /**\\n * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This\\n * \\\"original\\\" value is cached during construction of the vault contract. If this read operation fails (e.g., the\\n * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.\\n *\\n * See {IERC20Metadata-decimals}.\\n */\\n function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {\\n return _underlyingDecimals + _decimalsOffset();\\n }\\n\\n /** @dev See {IERC4626-asset}. */\\n function asset() public view virtual returns (address) {\\n return address(_asset);\\n }\\n\\n /** @dev See {IERC4626-totalAssets}. */\\n function totalAssets() public view virtual returns (uint256) {\\n return _asset.balanceOf(address(this));\\n }\\n\\n /** @dev See {IERC4626-convertToShares}. */\\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-convertToAssets}. */\\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-maxDeposit}. */\\n function maxDeposit(address) public view virtual returns (uint256) {\\n return type(uint256).max;\\n }\\n\\n /** @dev See {IERC4626-maxMint}. */\\n function maxMint(address) public view virtual returns (uint256) {\\n return type(uint256).max;\\n }\\n\\n /** @dev See {IERC4626-maxWithdraw}. */\\n function maxWithdraw(address owner) public view virtual returns (uint256) {\\n return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-maxRedeem}. */\\n function maxRedeem(address owner) public view virtual returns (uint256) {\\n return balanceOf(owner);\\n }\\n\\n /** @dev See {IERC4626-previewDeposit}. */\\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-previewMint}. */\\n function previewMint(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Ceil);\\n }\\n\\n /** @dev See {IERC4626-previewWithdraw}. */\\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Ceil);\\n }\\n\\n /** @dev See {IERC4626-previewRedeem}. */\\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-deposit}. */\\n function deposit(uint256 assets, address receiver) public virtual returns (uint256) {\\n uint256 maxAssets = maxDeposit(receiver);\\n if (assets > maxAssets) {\\n revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);\\n }\\n\\n uint256 shares = previewDeposit(assets);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-mint}.\\n *\\n * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.\\n * In this case, the shares will be minted without requiring any assets to be deposited.\\n */\\n function mint(uint256 shares, address receiver) public virtual returns (uint256) {\\n uint256 maxShares = maxMint(receiver);\\n if (shares > maxShares) {\\n revert ERC4626ExceededMaxMint(receiver, shares, maxShares);\\n }\\n\\n uint256 assets = previewMint(shares);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return assets;\\n }\\n\\n /** @dev See {IERC4626-withdraw}. */\\n function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {\\n uint256 maxAssets = maxWithdraw(owner);\\n if (assets > maxAssets) {\\n revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);\\n }\\n\\n uint256 shares = previewWithdraw(assets);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-redeem}. */\\n function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {\\n uint256 maxShares = maxRedeem(owner);\\n if (shares > maxShares) {\\n revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);\\n }\\n\\n uint256 assets = previewRedeem(shares);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return assets;\\n }\\n\\n /**\\n * @dev Internal conversion function (from assets to shares) with support for rounding direction.\\n */\\n function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {\\n return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);\\n }\\n\\n /**\\n * @dev Internal conversion function (from shares to assets) with support for rounding direction.\\n */\\n function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {\\n return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);\\n }\\n\\n /**\\n * @dev Deposit/mint common workflow.\\n */\\n function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {\\n // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the\\n // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\\n // assets are transferred and before the shares are minted, which is a valid state.\\n // slither-disable-next-line reentrancy-no-eth\\n SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);\\n _mint(receiver, shares);\\n\\n emit Deposit(caller, receiver, assets, shares);\\n }\\n\\n /**\\n * @dev Withdraw/redeem common workflow.\\n */\\n function _withdraw(\\n address caller,\\n address receiver,\\n address owner,\\n uint256 assets,\\n uint256 shares\\n ) internal virtual {\\n if (caller != owner) {\\n _spendAllowance(owner, caller, shares);\\n }\\n\\n // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\\n // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\\n // shares are burned and after the assets are transferred, which is a valid state.\\n _burn(owner, shares);\\n SafeERC20.safeTransfer(_asset, receiver, assets);\\n\\n emit Withdraw(caller, receiver, owner, assets, shares);\\n }\\n\\n function _decimalsOffset() internal view virtual returns (uint8) {\\n return 0;\\n }\\n}\\n\",\"keccak256\":\"0x1837547e04d5fe5334eeb77a345683c22995f1e7aa033020757ddf83a80fc72d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../IERC20.sol\\\";\\n\\n/**\\n * @dev Interface for the optional metadata functions from the ERC20 standard.\\n */\\ninterface IERC20Metadata is IERC20 {\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() external view returns (string memory);\\n\\n /**\\n * @dev Returns the symbol of the token.\\n */\\n function symbol() external view returns (string memory);\\n\\n /**\\n * @dev Returns the decimals places of the token.\\n */\\n function decimals() external view returns (uint8);\\n}\\n\",\"keccak256\":\"0xaa761817f6cd7892fcf158b3c776b34551cde36f48ff9703d53898bc45a94ea2\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\\n *\\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\\n * need to send a transaction, and thus is not required to hold Ether at all.\\n *\\n * ==== Security Considerations\\n *\\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\\n * generally recommended is:\\n *\\n * ```solidity\\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\\n * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\\n * doThing(..., value);\\n * }\\n *\\n * function doThing(..., uint256 value) public {\\n * token.safeTransferFrom(msg.sender, address(this), value);\\n * ...\\n * }\\n * ```\\n *\\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\\n * {SafeERC20-safeTransferFrom}).\\n *\\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\\n * contracts should have entry points that don't rely on permit.\\n */\\ninterface IERC20Permit {\\n /**\\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\\n * given ``owner``'s signed approval.\\n *\\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\\n * ordering also apply here.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n * - `deadline` must be a timestamp in the future.\\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\\n * over the EIP712-formatted function arguments.\\n * - the signature must use ``owner``'s current nonce (see {nonces}).\\n *\\n * For more information on the signature format, see the\\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\\n * section].\\n *\\n * CAUTION: See Security Considerations above.\\n */\\n function permit(\\n address owner,\\n address spender,\\n uint256 value,\\n uint256 deadline,\\n uint8 v,\\n bytes32 r,\\n bytes32 s\\n ) external;\\n\\n /**\\n * @dev Returns the current nonce for `owner`. This value must be\\n * included whenever a signature is generated for {permit}.\\n *\\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\\n * prevents a signature from being used multiple times.\\n */\\n function nonces(address owner) external view returns (uint256);\\n\\n /**\\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\\n */\\n // solhint-disable-next-line func-name-mixedcase\\n function DOMAIN_SEPARATOR() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0x6008dabfe393240d73d7dd7688033f72740d570aa422254d29a7dce8568f3aff\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../IERC20.sol\\\";\\nimport {IERC20Permit} from \\\"../extensions/IERC20Permit.sol\\\";\\nimport {Address} from \\\"../../../utils/Address.sol\\\";\\n\\n/**\\n * @title SafeERC20\\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\\n * contract returns false). Tokens that return no value (and instead revert or\\n * throw on failure) are also supported, non-reverting calls are assumed to be\\n * successful.\\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\\n */\\nlibrary SafeERC20 {\\n using Address for address;\\n\\n /**\\n * @dev An operation with an ERC20 token failed.\\n */\\n error SafeERC20FailedOperation(address token);\\n\\n /**\\n * @dev Indicates a failed `decreaseAllowance` request.\\n */\\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\\n\\n /**\\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful.\\n */\\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\\n }\\n\\n /**\\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\\n */\\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\\n }\\n\\n /**\\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful.\\n */\\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\\n uint256 oldAllowance = token.allowance(address(this), spender);\\n forceApprove(token, spender, oldAllowance + value);\\n }\\n\\n /**\\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\\n * value, non-reverting calls are assumed to be successful.\\n */\\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\\n unchecked {\\n uint256 currentAllowance = token.allowance(address(this), spender);\\n if (currentAllowance < requestedDecrease) {\\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\\n }\\n forceApprove(token, spender, currentAllowance - requestedDecrease);\\n }\\n }\\n\\n /**\\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\\n * to be set to zero before setting it to a non-zero value, such as USDT.\\n */\\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\\n\\n if (!_callOptionalReturnBool(token, approvalCall)) {\\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\\n _callOptionalReturn(token, approvalCall);\\n }\\n }\\n\\n /**\\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\\n * on the return value: the return value is optional (but if data is returned, it must not be false).\\n * @param token The token targeted by the call.\\n * @param data The call data (encoded using abi.encode or one of its variants).\\n */\\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\\n // the target address contains contract code and also asserts for success in the low-level call.\\n\\n bytes memory returndata = address(token).functionCall(data);\\n if (returndata.length != 0 && !abi.decode(returndata, (bool))) {\\n revert SafeERC20FailedOperation(address(token));\\n }\\n }\\n\\n /**\\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\\n * on the return value: the return value is optional (but if data is returned, it must not be false).\\n * @param token The token targeted by the call.\\n * @param data The call data (encoded using abi.encode or one of its variants).\\n *\\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\\n */\\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\\n // and not revert is the subcall reverts.\\n\\n (bool success, bytes memory returndata) = address(token).call(data);\\n return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;\\n }\\n}\\n\",\"keccak256\":\"0x37bb49513c49c87c4642a891b13b63571bc87013dde806617aa1efb54605f386\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Address.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary Address {\\n /**\\n * @dev The ETH balance of the account is not enough to perform the operation.\\n */\\n error AddressInsufficientBalance(address account);\\n\\n /**\\n * @dev There's no code at `target` (it is not a contract).\\n */\\n error AddressEmptyCode(address target);\\n\\n /**\\n * @dev A call to an address target failed. The target may have reverted.\\n */\\n error FailedInnerCall();\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n if (address(this).balance < amount) {\\n revert AddressInsufficientBalance(address(this));\\n }\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n if (!success) {\\n revert FailedInnerCall();\\n }\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason or custom error, it is bubbled\\n * up by this function (like regular Solidity function calls). However, if\\n * the call reverted with no returned reason, this function reverts with a\\n * {FailedInnerCall} error.\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n */\\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\\n if (address(this).balance < value) {\\n revert AddressInsufficientBalance(address(this));\\n }\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a delegate call.\\n */\\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.delegatecall(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\\n * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\\n * unsuccessful call.\\n */\\n function verifyCallResultFromTarget(\\n address target,\\n bool success,\\n bytes memory returndata\\n ) internal view returns (bytes memory) {\\n if (!success) {\\n _revert(returndata);\\n } else {\\n // only check if target is a contract if the call was successful and the return data is empty\\n // otherwise we already know that it was a contract\\n if (returndata.length == 0 && target.code.length == 0) {\\n revert AddressEmptyCode(target);\\n }\\n return returndata;\\n }\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\\n * revert reason or with a default {FailedInnerCall} error.\\n */\\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\\n if (!success) {\\n _revert(returndata);\\n } else {\\n return returndata;\\n }\\n }\\n\\n /**\\n * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\\n */\\n function _revert(bytes memory returndata) private pure {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n /// @solidity memory-safe-assembly\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert FailedInnerCall();\\n }\\n }\\n}\\n\",\"keccak256\":\"0xaf28a975a78550e45f65e559a3ad6a5ad43b9b8a37366999abd1b7084eb70721\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Context.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Provides information about the current execution context, including the\\n * sender of the transaction and its data. While these are generally available\\n * via msg.sender and msg.data, they should not be accessed in such a direct\\n * manner, since when dealing with meta-transactions the account sending and\\n * paying for execution may not be the actual sender (as far as an application\\n * is concerned).\\n *\\n * This contract is only required for intermediate, library-like contracts.\\n */\\nabstract contract Context {\\n function _msgSender() internal view virtual returns (address) {\\n return msg.sender;\\n }\\n\\n function _msgData() internal view virtual returns (bytes calldata) {\\n return msg.data;\\n }\\n}\\n\",\"keccak256\":\"0x75a4ee64c68dbd5f38bddd06e664a64c8271b4caa554fb6f0607dfd672bb4bf3\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/math/Math.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Standard math utilities missing in the Solidity language.\\n */\\nlibrary Math {\\n /**\\n * @dev Muldiv operation overflow.\\n */\\n error MathOverflowedMulDiv();\\n\\n enum Rounding {\\n Floor, // Toward negative infinity\\n Ceil, // Toward positive infinity\\n Trunc, // Toward zero\\n Expand // Away from zero\\n }\\n\\n /**\\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\\n */\\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n uint256 c = a + b;\\n if (c < a) return (false, 0);\\n return (true, c);\\n }\\n }\\n\\n /**\\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\\n */\\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b > a) return (false, 0);\\n return (true, a - b);\\n }\\n }\\n\\n /**\\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\\n */\\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\\n // benefit is lost if 'b' is also tested.\\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\\n if (a == 0) return (true, 0);\\n uint256 c = a * b;\\n if (c / a != b) return (false, 0);\\n return (true, c);\\n }\\n }\\n\\n /**\\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\\n */\\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b == 0) return (false, 0);\\n return (true, a / b);\\n }\\n }\\n\\n /**\\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\\n */\\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b == 0) return (false, 0);\\n return (true, a % b);\\n }\\n }\\n\\n /**\\n * @dev Returns the largest of two numbers.\\n */\\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a > b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the smallest of two numbers.\\n */\\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a < b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the average of two numbers. The result is rounded towards\\n * zero.\\n */\\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\\n // (a + b) / 2 can overflow.\\n return (a & b) + (a ^ b) / 2;\\n }\\n\\n /**\\n * @dev Returns the ceiling of the division of two numbers.\\n *\\n * This differs from standard division with `/` in that it rounds towards infinity instead\\n * of rounding towards zero.\\n */\\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\\n if (b == 0) {\\n // Guarantee the same behavior as in a regular Solidity division.\\n return a / b;\\n }\\n\\n // (a + b - 1) / b can overflow on addition, so we distribute.\\n return a == 0 ? 0 : (a - 1) / b + 1;\\n }\\n\\n /**\\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\\n * denominator == 0.\\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\\n * Uniswap Labs also under MIT license.\\n */\\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\\n unchecked {\\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\\n // variables such that product = prod1 * 2^256 + prod0.\\n uint256 prod0 = x * y; // Least significant 256 bits of the product\\n uint256 prod1; // Most significant 256 bits of the product\\n assembly {\\n let mm := mulmod(x, y, not(0))\\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\\n }\\n\\n // Handle non-overflow cases, 256 by 256 division.\\n if (prod1 == 0) {\\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\\n // The surrounding unchecked block does not change this fact.\\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\\n return prod0 / denominator;\\n }\\n\\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\\n if (denominator <= prod1) {\\n revert MathOverflowedMulDiv();\\n }\\n\\n ///////////////////////////////////////////////\\n // 512 by 256 division.\\n ///////////////////////////////////////////////\\n\\n // Make division exact by subtracting the remainder from [prod1 prod0].\\n uint256 remainder;\\n assembly {\\n // Compute remainder using mulmod.\\n remainder := mulmod(x, y, denominator)\\n\\n // Subtract 256 bit number from 512 bit number.\\n prod1 := sub(prod1, gt(remainder, prod0))\\n prod0 := sub(prod0, remainder)\\n }\\n\\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\\n\\n uint256 twos = denominator & (0 - denominator);\\n assembly {\\n // Divide denominator by twos.\\n denominator := div(denominator, twos)\\n\\n // Divide [prod1 prod0] by twos.\\n prod0 := div(prod0, twos)\\n\\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\\n twos := add(div(sub(0, twos), twos), 1)\\n }\\n\\n // Shift in bits from prod1 into prod0.\\n prod0 |= prod1 * twos;\\n\\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\\n // four bits. That is, denominator * inv = 1 mod 2^4.\\n uint256 inverse = (3 * denominator) ^ 2;\\n\\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\\n // works in modular arithmetic, doubling the correct bits in each step.\\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\\n\\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\\n // is no longer required.\\n result = prod0 * inverse;\\n return result;\\n }\\n }\\n\\n /**\\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\\n */\\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\\n uint256 result = mulDiv(x, y, denominator);\\n if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\\n result += 1;\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\\n * towards zero.\\n *\\n * Inspired by Henry S. Warren, Jr.'s \\\"Hacker's Delight\\\" (Chapter 11).\\n */\\n function sqrt(uint256 a) internal pure returns (uint256) {\\n if (a == 0) {\\n return 0;\\n }\\n\\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\\n //\\n // We know that the \\\"msb\\\" (most significant bit) of our target number `a` is a power of 2 such that we have\\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\\n //\\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\\n // \\u2192 `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\\n // \\u2192 `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\\n //\\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\\n uint256 result = 1 << (log2(a) >> 1);\\n\\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\\n // into the expected uint128 result.\\n unchecked {\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n return min(result, a / result);\\n }\\n }\\n\\n /**\\n * @notice Calculates sqrt(a), following the selected rounding direction.\\n */\\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = sqrt(a);\\n return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 2 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 128;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 64;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 32;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 16;\\n }\\n if (value >> 8 > 0) {\\n value >>= 8;\\n result += 8;\\n }\\n if (value >> 4 > 0) {\\n value >>= 4;\\n result += 4;\\n }\\n if (value >> 2 > 0) {\\n value >>= 2;\\n result += 2;\\n }\\n if (value >> 1 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log2(value);\\n return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 10 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >= 10 ** 64) {\\n value /= 10 ** 64;\\n result += 64;\\n }\\n if (value >= 10 ** 32) {\\n value /= 10 ** 32;\\n result += 32;\\n }\\n if (value >= 10 ** 16) {\\n value /= 10 ** 16;\\n result += 16;\\n }\\n if (value >= 10 ** 8) {\\n value /= 10 ** 8;\\n result += 8;\\n }\\n if (value >= 10 ** 4) {\\n value /= 10 ** 4;\\n result += 4;\\n }\\n if (value >= 10 ** 2) {\\n value /= 10 ** 2;\\n result += 2;\\n }\\n if (value >= 10 ** 1) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log10(value);\\n return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 256 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n *\\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\\n */\\n function log256(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 16;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 8;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 4;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 2;\\n }\\n if (value >> 8 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log256(value);\\n return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\\n */\\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\\n return uint8(rounding) % 2 == 1;\\n }\\n}\\n\",\"keccak256\":\"0x005ec64c6313f0555d59e278f9a7a5ab2db5bdc72a027f255a37c327af1ec02d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/math/SafeCast.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)\\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\\n * checks.\\n *\\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\\n * easily result in undesired exploitation or bugs, since developers usually\\n * assume that overflows raise errors. `SafeCast` restores this intuition by\\n * reverting the transaction when such an operation overflows.\\n *\\n * Using this library instead of the unchecked operations eliminates an entire\\n * class of bugs, so it's recommended to use it always.\\n */\\nlibrary SafeCast {\\n /**\\n * @dev Value doesn't fit in an uint of `bits` size.\\n */\\n error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\\n\\n /**\\n * @dev An int value doesn't fit in an uint of `bits` size.\\n */\\n error SafeCastOverflowedIntToUint(int256 value);\\n\\n /**\\n * @dev Value doesn't fit in an int of `bits` size.\\n */\\n error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\\n\\n /**\\n * @dev An uint value doesn't fit in an int of `bits` size.\\n */\\n error SafeCastOverflowedUintToInt(uint256 value);\\n\\n /**\\n * @dev Returns the downcasted uint248 from uint256, reverting on\\n * overflow (when the input is greater than largest uint248).\\n *\\n * Counterpart to Solidity's `uint248` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 248 bits\\n */\\n function toUint248(uint256 value) internal pure returns (uint248) {\\n if (value > type(uint248).max) {\\n revert SafeCastOverflowedUintDowncast(248, value);\\n }\\n return uint248(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint240 from uint256, reverting on\\n * overflow (when the input is greater than largest uint240).\\n *\\n * Counterpart to Solidity's `uint240` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 240 bits\\n */\\n function toUint240(uint256 value) internal pure returns (uint240) {\\n if (value > type(uint240).max) {\\n revert SafeCastOverflowedUintDowncast(240, value);\\n }\\n return uint240(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint232 from uint256, reverting on\\n * overflow (when the input is greater than largest uint232).\\n *\\n * Counterpart to Solidity's `uint232` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 232 bits\\n */\\n function toUint232(uint256 value) internal pure returns (uint232) {\\n if (value > type(uint232).max) {\\n revert SafeCastOverflowedUintDowncast(232, value);\\n }\\n return uint232(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint224 from uint256, reverting on\\n * overflow (when the input is greater than largest uint224).\\n *\\n * Counterpart to Solidity's `uint224` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 224 bits\\n */\\n function toUint224(uint256 value) internal pure returns (uint224) {\\n if (value > type(uint224).max) {\\n revert SafeCastOverflowedUintDowncast(224, value);\\n }\\n return uint224(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint216 from uint256, reverting on\\n * overflow (when the input is greater than largest uint216).\\n *\\n * Counterpart to Solidity's `uint216` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 216 bits\\n */\\n function toUint216(uint256 value) internal pure returns (uint216) {\\n if (value > type(uint216).max) {\\n revert SafeCastOverflowedUintDowncast(216, value);\\n }\\n return uint216(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint208 from uint256, reverting on\\n * overflow (when the input is greater than largest uint208).\\n *\\n * Counterpart to Solidity's `uint208` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 208 bits\\n */\\n function toUint208(uint256 value) internal pure returns (uint208) {\\n if (value > type(uint208).max) {\\n revert SafeCastOverflowedUintDowncast(208, value);\\n }\\n return uint208(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint200 from uint256, reverting on\\n * overflow (when the input is greater than largest uint200).\\n *\\n * Counterpart to Solidity's `uint200` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 200 bits\\n */\\n function toUint200(uint256 value) internal pure returns (uint200) {\\n if (value > type(uint200).max) {\\n revert SafeCastOverflowedUintDowncast(200, value);\\n }\\n return uint200(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint192 from uint256, reverting on\\n * overflow (when the input is greater than largest uint192).\\n *\\n * Counterpart to Solidity's `uint192` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 192 bits\\n */\\n function toUint192(uint256 value) internal pure returns (uint192) {\\n if (value > type(uint192).max) {\\n revert SafeCastOverflowedUintDowncast(192, value);\\n }\\n return uint192(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint184 from uint256, reverting on\\n * overflow (when the input is greater than largest uint184).\\n *\\n * Counterpart to Solidity's `uint184` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 184 bits\\n */\\n function toUint184(uint256 value) internal pure returns (uint184) {\\n if (value > type(uint184).max) {\\n revert SafeCastOverflowedUintDowncast(184, value);\\n }\\n return uint184(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint176 from uint256, reverting on\\n * overflow (when the input is greater than largest uint176).\\n *\\n * Counterpart to Solidity's `uint176` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 176 bits\\n */\\n function toUint176(uint256 value) internal pure returns (uint176) {\\n if (value > type(uint176).max) {\\n revert SafeCastOverflowedUintDowncast(176, value);\\n }\\n return uint176(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint168 from uint256, reverting on\\n * overflow (when the input is greater than largest uint168).\\n *\\n * Counterpart to Solidity's `uint168` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 168 bits\\n */\\n function toUint168(uint256 value) internal pure returns (uint168) {\\n if (value > type(uint168).max) {\\n revert SafeCastOverflowedUintDowncast(168, value);\\n }\\n return uint168(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint160 from uint256, reverting on\\n * overflow (when the input is greater than largest uint160).\\n *\\n * Counterpart to Solidity's `uint160` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 160 bits\\n */\\n function toUint160(uint256 value) internal pure returns (uint160) {\\n if (value > type(uint160).max) {\\n revert SafeCastOverflowedUintDowncast(160, value);\\n }\\n return uint160(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint152 from uint256, reverting on\\n * overflow (when the input is greater than largest uint152).\\n *\\n * Counterpart to Solidity's `uint152` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 152 bits\\n */\\n function toUint152(uint256 value) internal pure returns (uint152) {\\n if (value > type(uint152).max) {\\n revert SafeCastOverflowedUintDowncast(152, value);\\n }\\n return uint152(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint144 from uint256, reverting on\\n * overflow (when the input is greater than largest uint144).\\n *\\n * Counterpart to Solidity's `uint144` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 144 bits\\n */\\n function toUint144(uint256 value) internal pure returns (uint144) {\\n if (value > type(uint144).max) {\\n revert SafeCastOverflowedUintDowncast(144, value);\\n }\\n return uint144(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint136 from uint256, reverting on\\n * overflow (when the input is greater than largest uint136).\\n *\\n * Counterpart to Solidity's `uint136` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 136 bits\\n */\\n function toUint136(uint256 value) internal pure returns (uint136) {\\n if (value > type(uint136).max) {\\n revert SafeCastOverflowedUintDowncast(136, value);\\n }\\n return uint136(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint128 from uint256, reverting on\\n * overflow (when the input is greater than largest uint128).\\n *\\n * Counterpart to Solidity's `uint128` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 128 bits\\n */\\n function toUint128(uint256 value) internal pure returns (uint128) {\\n if (value > type(uint128).max) {\\n revert SafeCastOverflowedUintDowncast(128, value);\\n }\\n return uint128(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint120 from uint256, reverting on\\n * overflow (when the input is greater than largest uint120).\\n *\\n * Counterpart to Solidity's `uint120` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 120 bits\\n */\\n function toUint120(uint256 value) internal pure returns (uint120) {\\n if (value > type(uint120).max) {\\n revert SafeCastOverflowedUintDowncast(120, value);\\n }\\n return uint120(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint112 from uint256, reverting on\\n * overflow (when the input is greater than largest uint112).\\n *\\n * Counterpart to Solidity's `uint112` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 112 bits\\n */\\n function toUint112(uint256 value) internal pure returns (uint112) {\\n if (value > type(uint112).max) {\\n revert SafeCastOverflowedUintDowncast(112, value);\\n }\\n return uint112(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint104 from uint256, reverting on\\n * overflow (when the input is greater than largest uint104).\\n *\\n * Counterpart to Solidity's `uint104` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 104 bits\\n */\\n function toUint104(uint256 value) internal pure returns (uint104) {\\n if (value > type(uint104).max) {\\n revert SafeCastOverflowedUintDowncast(104, value);\\n }\\n return uint104(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint96 from uint256, reverting on\\n * overflow (when the input is greater than largest uint96).\\n *\\n * Counterpart to Solidity's `uint96` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 96 bits\\n */\\n function toUint96(uint256 value) internal pure returns (uint96) {\\n if (value > type(uint96).max) {\\n revert SafeCastOverflowedUintDowncast(96, value);\\n }\\n return uint96(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint88 from uint256, reverting on\\n * overflow (when the input is greater than largest uint88).\\n *\\n * Counterpart to Solidity's `uint88` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 88 bits\\n */\\n function toUint88(uint256 value) internal pure returns (uint88) {\\n if (value > type(uint88).max) {\\n revert SafeCastOverflowedUintDowncast(88, value);\\n }\\n return uint88(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint80 from uint256, reverting on\\n * overflow (when the input is greater than largest uint80).\\n *\\n * Counterpart to Solidity's `uint80` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 80 bits\\n */\\n function toUint80(uint256 value) internal pure returns (uint80) {\\n if (value > type(uint80).max) {\\n revert SafeCastOverflowedUintDowncast(80, value);\\n }\\n return uint80(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint72 from uint256, reverting on\\n * overflow (when the input is greater than largest uint72).\\n *\\n * Counterpart to Solidity's `uint72` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 72 bits\\n */\\n function toUint72(uint256 value) internal pure returns (uint72) {\\n if (value > type(uint72).max) {\\n revert SafeCastOverflowedUintDowncast(72, value);\\n }\\n return uint72(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint64 from uint256, reverting on\\n * overflow (when the input is greater than largest uint64).\\n *\\n * Counterpart to Solidity's `uint64` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 64 bits\\n */\\n function toUint64(uint256 value) internal pure returns (uint64) {\\n if (value > type(uint64).max) {\\n revert SafeCastOverflowedUintDowncast(64, value);\\n }\\n return uint64(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint56 from uint256, reverting on\\n * overflow (when the input is greater than largest uint56).\\n *\\n * Counterpart to Solidity's `uint56` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 56 bits\\n */\\n function toUint56(uint256 value) internal pure returns (uint56) {\\n if (value > type(uint56).max) {\\n revert SafeCastOverflowedUintDowncast(56, value);\\n }\\n return uint56(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint48 from uint256, reverting on\\n * overflow (when the input is greater than largest uint48).\\n *\\n * Counterpart to Solidity's `uint48` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 48 bits\\n */\\n function toUint48(uint256 value) internal pure returns (uint48) {\\n if (value > type(uint48).max) {\\n revert SafeCastOverflowedUintDowncast(48, value);\\n }\\n return uint48(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint40 from uint256, reverting on\\n * overflow (when the input is greater than largest uint40).\\n *\\n * Counterpart to Solidity's `uint40` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 40 bits\\n */\\n function toUint40(uint256 value) internal pure returns (uint40) {\\n if (value > type(uint40).max) {\\n revert SafeCastOverflowedUintDowncast(40, value);\\n }\\n return uint40(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint32 from uint256, reverting on\\n * overflow (when the input is greater than largest uint32).\\n *\\n * Counterpart to Solidity's `uint32` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 32 bits\\n */\\n function toUint32(uint256 value) internal pure returns (uint32) {\\n if (value > type(uint32).max) {\\n revert SafeCastOverflowedUintDowncast(32, value);\\n }\\n return uint32(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint24 from uint256, reverting on\\n * overflow (when the input is greater than largest uint24).\\n *\\n * Counterpart to Solidity's `uint24` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 24 bits\\n */\\n function toUint24(uint256 value) internal pure returns (uint24) {\\n if (value > type(uint24).max) {\\n revert SafeCastOverflowedUintDowncast(24, value);\\n }\\n return uint24(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint16 from uint256, reverting on\\n * overflow (when the input is greater than largest uint16).\\n *\\n * Counterpart to Solidity's `uint16` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 16 bits\\n */\\n function toUint16(uint256 value) internal pure returns (uint16) {\\n if (value > type(uint16).max) {\\n revert SafeCastOverflowedUintDowncast(16, value);\\n }\\n return uint16(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint8 from uint256, reverting on\\n * overflow (when the input is greater than largest uint8).\\n *\\n * Counterpart to Solidity's `uint8` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 8 bits\\n */\\n function toUint8(uint256 value) internal pure returns (uint8) {\\n if (value > type(uint8).max) {\\n revert SafeCastOverflowedUintDowncast(8, value);\\n }\\n return uint8(value);\\n }\\n\\n /**\\n * @dev Converts a signed int256 into an unsigned uint256.\\n *\\n * Requirements:\\n *\\n * - input must be greater than or equal to 0.\\n */\\n function toUint256(int256 value) internal pure returns (uint256) {\\n if (value < 0) {\\n revert SafeCastOverflowedIntToUint(value);\\n }\\n return uint256(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted int248 from int256, reverting on\\n * overflow (when the input is less than smallest int248 or\\n * greater than largest int248).\\n *\\n * Counterpart to Solidity's `int248` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 248 bits\\n */\\n function toInt248(int256 value) internal pure returns (int248 downcasted) {\\n downcasted = int248(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(248, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int240 from int256, reverting on\\n * overflow (when the input is less than smallest int240 or\\n * greater than largest int240).\\n *\\n * Counterpart to Solidity's `int240` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 240 bits\\n */\\n function toInt240(int256 value) internal pure returns (int240 downcasted) {\\n downcasted = int240(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(240, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int232 from int256, reverting on\\n * overflow (when the input is less than smallest int232 or\\n * greater than largest int232).\\n *\\n * Counterpart to Solidity's `int232` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 232 bits\\n */\\n function toInt232(int256 value) internal pure returns (int232 downcasted) {\\n downcasted = int232(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(232, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int224 from int256, reverting on\\n * overflow (when the input is less than smallest int224 or\\n * greater than largest int224).\\n *\\n * Counterpart to Solidity's `int224` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 224 bits\\n */\\n function toInt224(int256 value) internal pure returns (int224 downcasted) {\\n downcasted = int224(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(224, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int216 from int256, reverting on\\n * overflow (when the input is less than smallest int216 or\\n * greater than largest int216).\\n *\\n * Counterpart to Solidity's `int216` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 216 bits\\n */\\n function toInt216(int256 value) internal pure returns (int216 downcasted) {\\n downcasted = int216(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(216, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int208 from int256, reverting on\\n * overflow (when the input is less than smallest int208 or\\n * greater than largest int208).\\n *\\n * Counterpart to Solidity's `int208` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 208 bits\\n */\\n function toInt208(int256 value) internal pure returns (int208 downcasted) {\\n downcasted = int208(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(208, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int200 from int256, reverting on\\n * overflow (when the input is less than smallest int200 or\\n * greater than largest int200).\\n *\\n * Counterpart to Solidity's `int200` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 200 bits\\n */\\n function toInt200(int256 value) internal pure returns (int200 downcasted) {\\n downcasted = int200(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(200, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int192 from int256, reverting on\\n * overflow (when the input is less than smallest int192 or\\n * greater than largest int192).\\n *\\n * Counterpart to Solidity's `int192` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 192 bits\\n */\\n function toInt192(int256 value) internal pure returns (int192 downcasted) {\\n downcasted = int192(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(192, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int184 from int256, reverting on\\n * overflow (when the input is less than smallest int184 or\\n * greater than largest int184).\\n *\\n * Counterpart to Solidity's `int184` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 184 bits\\n */\\n function toInt184(int256 value) internal pure returns (int184 downcasted) {\\n downcasted = int184(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(184, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int176 from int256, reverting on\\n * overflow (when the input is less than smallest int176 or\\n * greater than largest int176).\\n *\\n * Counterpart to Solidity's `int176` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 176 bits\\n */\\n function toInt176(int256 value) internal pure returns (int176 downcasted) {\\n downcasted = int176(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(176, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int168 from int256, reverting on\\n * overflow (when the input is less than smallest int168 or\\n * greater than largest int168).\\n *\\n * Counterpart to Solidity's `int168` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 168 bits\\n */\\n function toInt168(int256 value) internal pure returns (int168 downcasted) {\\n downcasted = int168(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(168, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int160 from int256, reverting on\\n * overflow (when the input is less than smallest int160 or\\n * greater than largest int160).\\n *\\n * Counterpart to Solidity's `int160` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 160 bits\\n */\\n function toInt160(int256 value) internal pure returns (int160 downcasted) {\\n downcasted = int160(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(160, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int152 from int256, reverting on\\n * overflow (when the input is less than smallest int152 or\\n * greater than largest int152).\\n *\\n * Counterpart to Solidity's `int152` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 152 bits\\n */\\n function toInt152(int256 value) internal pure returns (int152 downcasted) {\\n downcasted = int152(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(152, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int144 from int256, reverting on\\n * overflow (when the input is less than smallest int144 or\\n * greater than largest int144).\\n *\\n * Counterpart to Solidity's `int144` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 144 bits\\n */\\n function toInt144(int256 value) internal pure returns (int144 downcasted) {\\n downcasted = int144(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(144, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int136 from int256, reverting on\\n * overflow (when the input is less than smallest int136 or\\n * greater than largest int136).\\n *\\n * Counterpart to Solidity's `int136` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 136 bits\\n */\\n function toInt136(int256 value) internal pure returns (int136 downcasted) {\\n downcasted = int136(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(136, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int128 from int256, reverting on\\n * overflow (when the input is less than smallest int128 or\\n * greater than largest int128).\\n *\\n * Counterpart to Solidity's `int128` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 128 bits\\n */\\n function toInt128(int256 value) internal pure returns (int128 downcasted) {\\n downcasted = int128(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(128, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int120 from int256, reverting on\\n * overflow (when the input is less than smallest int120 or\\n * greater than largest int120).\\n *\\n * Counterpart to Solidity's `int120` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 120 bits\\n */\\n function toInt120(int256 value) internal pure returns (int120 downcasted) {\\n downcasted = int120(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(120, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int112 from int256, reverting on\\n * overflow (when the input is less than smallest int112 or\\n * greater than largest int112).\\n *\\n * Counterpart to Solidity's `int112` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 112 bits\\n */\\n function toInt112(int256 value) internal pure returns (int112 downcasted) {\\n downcasted = int112(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(112, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int104 from int256, reverting on\\n * overflow (when the input is less than smallest int104 or\\n * greater than largest int104).\\n *\\n * Counterpart to Solidity's `int104` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 104 bits\\n */\\n function toInt104(int256 value) internal pure returns (int104 downcasted) {\\n downcasted = int104(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(104, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int96 from int256, reverting on\\n * overflow (when the input is less than smallest int96 or\\n * greater than largest int96).\\n *\\n * Counterpart to Solidity's `int96` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 96 bits\\n */\\n function toInt96(int256 value) internal pure returns (int96 downcasted) {\\n downcasted = int96(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(96, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int88 from int256, reverting on\\n * overflow (when the input is less than smallest int88 or\\n * greater than largest int88).\\n *\\n * Counterpart to Solidity's `int88` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 88 bits\\n */\\n function toInt88(int256 value) internal pure returns (int88 downcasted) {\\n downcasted = int88(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(88, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int80 from int256, reverting on\\n * overflow (when the input is less than smallest int80 or\\n * greater than largest int80).\\n *\\n * Counterpart to Solidity's `int80` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 80 bits\\n */\\n function toInt80(int256 value) internal pure returns (int80 downcasted) {\\n downcasted = int80(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(80, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int72 from int256, reverting on\\n * overflow (when the input is less than smallest int72 or\\n * greater than largest int72).\\n *\\n * Counterpart to Solidity's `int72` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 72 bits\\n */\\n function toInt72(int256 value) internal pure returns (int72 downcasted) {\\n downcasted = int72(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(72, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int64 from int256, reverting on\\n * overflow (when the input is less than smallest int64 or\\n * greater than largest int64).\\n *\\n * Counterpart to Solidity's `int64` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 64 bits\\n */\\n function toInt64(int256 value) internal pure returns (int64 downcasted) {\\n downcasted = int64(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(64, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int56 from int256, reverting on\\n * overflow (when the input is less than smallest int56 or\\n * greater than largest int56).\\n *\\n * Counterpart to Solidity's `int56` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 56 bits\\n */\\n function toInt56(int256 value) internal pure returns (int56 downcasted) {\\n downcasted = int56(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(56, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int48 from int256, reverting on\\n * overflow (when the input is less than smallest int48 or\\n * greater than largest int48).\\n *\\n * Counterpart to Solidity's `int48` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 48 bits\\n */\\n function toInt48(int256 value) internal pure returns (int48 downcasted) {\\n downcasted = int48(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(48, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int40 from int256, reverting on\\n * overflow (when the input is less than smallest int40 or\\n * greater than largest int40).\\n *\\n * Counterpart to Solidity's `int40` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 40 bits\\n */\\n function toInt40(int256 value) internal pure returns (int40 downcasted) {\\n downcasted = int40(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(40, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int32 from int256, reverting on\\n * overflow (when the input is less than smallest int32 or\\n * greater than largest int32).\\n *\\n * Counterpart to Solidity's `int32` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 32 bits\\n */\\n function toInt32(int256 value) internal pure returns (int32 downcasted) {\\n downcasted = int32(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(32, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int24 from int256, reverting on\\n * overflow (when the input is less than smallest int24 or\\n * greater than largest int24).\\n *\\n * Counterpart to Solidity's `int24` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 24 bits\\n */\\n function toInt24(int256 value) internal pure returns (int24 downcasted) {\\n downcasted = int24(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(24, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int16 from int256, reverting on\\n * overflow (when the input is less than smallest int16 or\\n * greater than largest int16).\\n *\\n * Counterpart to Solidity's `int16` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 16 bits\\n */\\n function toInt16(int256 value) internal pure returns (int16 downcasted) {\\n downcasted = int16(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(16, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int8 from int256, reverting on\\n * overflow (when the input is less than smallest int8 or\\n * greater than largest int8).\\n *\\n * Counterpart to Solidity's `int8` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 8 bits\\n */\\n function toInt8(int256 value) internal pure returns (int8 downcasted) {\\n downcasted = int8(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(8, value);\\n }\\n }\\n\\n /**\\n * @dev Converts an unsigned uint256 into a signed int256.\\n *\\n * Requirements:\\n *\\n * - input must be less than or equal to maxInt256.\\n */\\n function toInt256(uint256 value) internal pure returns (int256) {\\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\\n if (value > uint256(type(int256).max)) {\\n revert SafeCastOverflowedUintToInt(value);\\n }\\n return int256(value);\\n }\\n}\\n\",\"keccak256\":\"0xe19a4d5f31d2861e7344e8e535e2feafb913d806d3e2b5fe7782741a2a7094fe\",\"license\":\"MIT\"},\"contracts/AcreBitcoinDepositor.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/access/Ownable2Step.sol\\\";\\nimport {SafeERC20} from \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport {IERC20} from \\\"@openzeppelin/contracts/token/ERC20/IERC20.sol\\\";\\nimport {SafeCast} from \\\"@openzeppelin/contracts/utils/math/SafeCast.sol\\\";\\n\\nimport \\\"@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol\\\";\\n\\nimport {stBTC} from \\\"./stBTC.sol\\\";\\n\\n// TODO: Make Upgradable\\n// TODO: Make Pausable\\n\\n/// @title Acre Bitcoin Depositor contract.\\n/// @notice The contract integrates Acre staking with tBTC minting.\\n/// User who wants to stake BTC in Acre should submit a Bitcoin transaction\\n/// to the most recently created off-chain ECDSA wallets of the tBTC Bridge\\n/// using pay-to-script-hash (P2SH) or pay-to-witness-script-hash (P2WSH)\\n/// containing hashed information about this Depositor contract address,\\n/// and staker's Ethereum address.\\n/// Then, the staker initiates tBTC minting by revealing their Ethereum\\n/// address along with their deposit blinding factor, refund public key\\n/// hash and refund locktime on the tBTC Bridge through this Depositor\\n/// contract.\\n/// The off-chain ECDSA wallet and Optimistic Minting bots listen for these\\n/// sorts of messages and when they get one, they check the Bitcoin network\\n/// to make sure the deposit lines up. Majority of tBTC minting is finalized\\n/// by the Optimistic Minting process, where Minter bot initializes\\n/// minting process and if there is no veto from the Guardians, the\\n/// process is finalized and tBTC minted to the Depositor address. If\\n/// the revealed deposit is not handled by the Optimistic Minting process\\n/// the off-chain ECDSA wallet may decide to pick the deposit transaction\\n/// for sweeping, and when the sweep operation is confirmed on the Bitcoin\\n/// network, the tBTC Bridge and tBTC vault mint the tBTC token to the\\n/// Depositor address. After tBTC is minted to the Depositor, on the stake\\n/// finalization tBTC is staked in stBTC contract and stBTC shares are emitted\\n/// to the staker.\\ncontract AcreBitcoinDepositor is AbstractTBTCDepositor, Ownable2Step {\\n using SafeERC20 for IERC20;\\n\\n /// @notice State of the stake request.\\n enum StakeRequestState {\\n Unknown,\\n Initialized,\\n Finalized,\\n Queued,\\n FinalizedFromQueue,\\n CancelledFromQueue\\n }\\n\\n struct StakeRequest {\\n // State of the stake request.\\n StakeRequestState state;\\n // The address to which the stBTC shares will be minted. Stored only when\\n // request is queued.\\n address staker;\\n // tBTC token amount to stake after deducting tBTC minting fees and the\\n // Depositor fee. Stored only when request is queued.\\n uint88 queuedAmount;\\n }\\n\\n /// @notice Mapping of stake requests.\\n /// @dev The key is a deposit key identifying the deposit.\\n mapping(uint256 => StakeRequest) public stakeRequests;\\n\\n /// @notice tBTC Token contract.\\n // TODO: Remove slither disable when introducing upgradeability.\\n // slither-disable-next-line immutable-states\\n IERC20 public tbtcToken;\\n\\n /// @notice stBTC contract.\\n // TODO: Remove slither disable when introducing upgradeability.\\n // slither-disable-next-line immutable-states\\n stBTC public stbtc;\\n\\n /// @notice Divisor used to compute the depositor fee taken from each deposit\\n /// and transferred to the treasury upon stake request finalization.\\n /// @dev That fee is computed as follows:\\n /// `depositorFee = depositedAmount / depositorFeeDivisor`\\n /// for example, if the depositor fee needs to be 2% of each deposit,\\n /// the `depositorFeeDivisor` should be set to `50` because\\n /// `1/50 = 0.02 = 2%`.\\n uint64 public depositorFeeDivisor;\\n\\n /// @notice Emitted when a stake request is initialized.\\n /// @dev Deposit details can be fetched from {{ Bridge.DepositRevealed }}\\n /// event emitted in the same transaction.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param caller Address that initialized the stake request.\\n /// @param staker The address to which the stBTC shares will be minted.\\n event StakeRequestInitialized(\\n uint256 indexed depositKey,\\n address indexed caller,\\n address indexed staker\\n );\\n\\n /// @notice Emitted when bridging completion has been notified.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param caller Address that notified about bridging completion.\\n /// @param referral Identifier of a partner in the referral program.\\n /// @param bridgedAmount Amount of tBTC tokens that was bridged by the tBTC bridge.\\n /// @param depositorFee Depositor fee amount.\\n event BridgingCompleted(\\n uint256 indexed depositKey,\\n address indexed caller,\\n uint16 indexed referral,\\n uint256 bridgedAmount,\\n uint256 depositorFee\\n );\\n\\n /// @notice Emitted when a stake request is finalized.\\n /// @dev Deposit details can be fetched from {{ ERC4626.Deposit }}\\n /// event emitted in the same transaction.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param caller Address that finalized the stake request.\\n /// @param stakedAmount Amount of staked tBTC tokens.\\n event StakeRequestFinalized(\\n uint256 indexed depositKey,\\n address indexed caller,\\n uint256 stakedAmount\\n );\\n\\n /// @notice Emitted when a stake request is queued.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param caller Address that finalized the stake request.\\n /// @param queuedAmount Amount of queued tBTC tokens.\\n event StakeRequestQueued(\\n uint256 indexed depositKey,\\n address indexed caller,\\n uint256 queuedAmount\\n );\\n\\n /// @notice Emitted when a stake request is finalized from the queue.\\n /// @dev Deposit details can be fetched from {{ ERC4626.Deposit }}\\n /// event emitted in the same transaction.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param caller Address that finalized the stake request.\\n /// @param stakedAmount Amount of staked tBTC tokens.\\n event StakeRequestFinalizedFromQueue(\\n uint256 indexed depositKey,\\n address indexed caller,\\n uint256 stakedAmount\\n );\\n\\n /// @notice Emitted when a queued stake request is cancelled.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param staker Address of the staker.\\n /// @param amountToStake Amount of queued tBTC tokens that got cancelled.\\n event StakeRequestCancelledFromQueue(\\n uint256 indexed depositKey,\\n address indexed staker,\\n uint256 amountToStake\\n );\\n\\n /// @notice Emitted when a depositor fee divisor is updated.\\n /// @param depositorFeeDivisor New value of the depositor fee divisor.\\n event DepositorFeeDivisorUpdated(uint64 depositorFeeDivisor);\\n\\n /// Reverts if the tBTC Token address is zero.\\n error TbtcTokenZeroAddress();\\n\\n /// Reverts if the stBTC address is zero.\\n error StbtcZeroAddress();\\n\\n /// @dev Staker address is zero.\\n error StakerIsZeroAddress();\\n\\n /// @dev Attempted to execute function for stake request in unexpected current\\n /// state.\\n error UnexpectedStakeRequestState(\\n StakeRequestState currentState,\\n StakeRequestState expectedState\\n );\\n\\n /// @dev Attempted to finalize bridging with depositor's contract tBTC balance\\n /// lower than the calculated bridged tBTC amount. This error means\\n /// that Governance should top-up the tBTC reserve for bridging fees\\n /// approximation.\\n error InsufficientTbtcBalance(\\n uint256 amountToStake,\\n uint256 currentBalance\\n );\\n\\n /// @dev Attempted to notify a bridging completion, while it was already\\n /// notified.\\n error BridgingCompletionAlreadyNotified();\\n\\n /// @dev Attempted to finalize a stake request, while bridging completion has\\n /// not been notified yet.\\n error BridgingNotCompleted();\\n\\n /// @dev Calculated depositor fee exceeds the amount of minted tBTC tokens.\\n error DepositorFeeExceedsBridgedAmount(\\n uint256 depositorFee,\\n uint256 bridgedAmount\\n );\\n\\n /// @dev Attempted to call bridging finalization for a stake request for\\n /// which the function was already called.\\n error BridgingFinalizationAlreadyCalled();\\n\\n /// @dev Attempted to finalize or cancel a stake request that was not added\\n /// to the queue, or was already finalized or cancelled.\\n error StakeRequestNotQueued();\\n\\n /// @dev Attempted to call function by an account that is not the staker.\\n error CallerNotStaker();\\n\\n /// @notice Acre Bitcoin Depositor contract constructor.\\n /// @param bridge tBTC Bridge contract instance.\\n /// @param tbtcVault tBTC Vault contract instance.\\n /// @param _tbtcToken tBTC token contract instance.\\n /// @param _stbtc stBTC contract instance.\\n // TODO: Move to initializer when making the contract upgradeable.\\n constructor(\\n address bridge,\\n address tbtcVault,\\n address _tbtcToken,\\n address _stbtc\\n ) Ownable(msg.sender) {\\n __AbstractTBTCDepositor_initialize(bridge, tbtcVault);\\n\\n if (address(_tbtcToken) == address(0)) {\\n revert TbtcTokenZeroAddress();\\n }\\n if (address(_stbtc) == address(0)) {\\n revert StbtcZeroAddress();\\n }\\n\\n tbtcToken = IERC20(_tbtcToken);\\n stbtc = stBTC(_stbtc);\\n\\n depositorFeeDivisor = 1000; // 1/1000 == 10bps == 0.1% == 0.001\\n }\\n\\n /// @notice This function allows staking process initialization for a Bitcoin\\n /// deposit made by an user with a P2(W)SH transaction. It uses the\\n /// supplied information to reveal a deposit to the tBTC Bridge contract.\\n /// @dev Requirements:\\n /// - The revealed vault address must match the TBTCVault address,\\n /// - All requirements from {Bridge#revealDepositWithExtraData}\\n /// function must be met.\\n /// - `staker` must be the staker address used in the P2(W)SH BTC\\n /// deposit transaction as part of the extra data.\\n /// - `referral` must be the referral info used in the P2(W)SH BTC\\n /// deposit transaction as part of the extra data.\\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\\n /// can be revealed only one time.\\n /// @param fundingTx Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.\\n /// @param reveal Deposit reveal data, see `IBridgeTypes.DepositRevealInfo`.\\n /// @param staker The address to which the stBTC shares will be minted.\\n /// @param referral Data used for referral program.\\n function initializeStake(\\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\\n IBridgeTypes.DepositRevealInfo calldata reveal,\\n address staker,\\n uint16 referral\\n ) external {\\n if (staker == address(0)) revert StakerIsZeroAddress();\\n\\n // We don't check if the request was already initialized, as this check\\n // is enforced in `_initializeDeposit` when calling the\\n // `Bridge.revealDepositWithExtraData` function.\\n uint256 depositKey = _initializeDeposit(\\n fundingTx,\\n reveal,\\n encodeExtraData(staker, referral)\\n );\\n\\n transitionStakeRequestState(\\n depositKey,\\n StakeRequestState.Unknown,\\n StakeRequestState.Initialized\\n );\\n\\n emit StakeRequestInitialized(depositKey, msg.sender, staker);\\n }\\n\\n /// @notice This function should be called for previously initialized stake\\n /// request, after tBTC bridging process was finalized.\\n /// It stakes the tBTC from the given deposit into stBTC, emitting the\\n /// stBTC shares to the staker specified in the deposit extra data\\n /// and using the referral provided in the extra data.\\n /// @dev In case depositing in stBTC vault fails (e.g. because of the\\n /// maximum deposit limit being reached), the `queueStake` function\\n /// should be called to add the stake request to the staking queue.\\n /// @param depositKey Deposit key identifying the deposit.\\n function finalizeStake(uint256 depositKey) external {\\n transitionStakeRequestState(\\n depositKey,\\n StakeRequestState.Initialized,\\n StakeRequestState.Finalized\\n );\\n\\n (uint256 amountToStake, address staker) = finalizeBridging(depositKey);\\n\\n emit StakeRequestFinalized(depositKey, msg.sender, amountToStake);\\n\\n // Deposit tBTC in stBTC.\\n tbtcToken.safeIncreaseAllowance(address(stbtc), amountToStake);\\n // slither-disable-next-line unused-return\\n stbtc.deposit(amountToStake, staker);\\n }\\n\\n /// @notice This function should be called for previously initialized stake\\n /// request, after tBTC bridging process was finalized, in case the\\n /// `finalizeStake` failed due to stBTC vault deposit limit\\n /// being reached.\\n /// @dev It queues the stake request, until the stBTC vault is ready to\\n /// accept the deposit. The request must be finalized with `finalizeQueuedStake`\\n /// after the limit is increased or other user withdraws their funds\\n /// from the stBTC contract to make place for another deposit.\\n /// The staker has a possibility to submit `cancelQueuedStake` that\\n /// will withdraw the minted tBTC token and abort staking process.\\n /// @param depositKey Deposit key identifying the deposit.\\n function queueStake(uint256 depositKey) external {\\n transitionStakeRequestState(\\n depositKey,\\n StakeRequestState.Initialized,\\n StakeRequestState.Queued\\n );\\n\\n StakeRequest storage request = stakeRequests[depositKey];\\n\\n uint256 amountToStake;\\n (amountToStake, request.staker) = finalizeBridging(depositKey);\\n\\n request.queuedAmount = SafeCast.toUint88(amountToStake);\\n\\n emit StakeRequestQueued(depositKey, msg.sender, request.queuedAmount);\\n }\\n\\n /// @notice This function should be called for previously queued stake\\n /// request, when stBTC vault is able to accept a deposit.\\n /// @param depositKey Deposit key identifying the deposit.\\n function finalizeQueuedStake(uint256 depositKey) external {\\n transitionStakeRequestState(\\n depositKey,\\n StakeRequestState.Queued,\\n StakeRequestState.FinalizedFromQueue\\n );\\n\\n StakeRequest storage request = stakeRequests[depositKey];\\n\\n if (request.queuedAmount == 0) revert StakeRequestNotQueued();\\n\\n uint256 amountToStake = request.queuedAmount;\\n delete (request.queuedAmount);\\n\\n emit StakeRequestFinalizedFromQueue(\\n depositKey,\\n msg.sender,\\n amountToStake\\n );\\n\\n // Deposit tBTC in stBTC.\\n tbtcToken.safeIncreaseAllowance(address(stbtc), amountToStake);\\n // slither-disable-next-line unused-return\\n stbtc.deposit(amountToStake, request.staker);\\n }\\n\\n /// @notice Cancel queued stake.\\n /// The function can be called by the staker to recover tBTC that cannot\\n /// be finalized to stake in stBTC contract due to a deposit limit being\\n /// reached.\\n /// @dev This function can be called only after the stake request was added\\n /// to queue.\\n /// @dev Only staker provided in the extra data of the stake request can\\n /// call this function.\\n /// @param depositKey Deposit key identifying the deposit.\\n function cancelQueuedStake(uint256 depositKey) external {\\n transitionStakeRequestState(\\n depositKey,\\n StakeRequestState.Queued,\\n StakeRequestState.CancelledFromQueue\\n );\\n\\n StakeRequest storage request = stakeRequests[depositKey];\\n\\n if (request.queuedAmount == 0) revert StakeRequestNotQueued();\\n\\n // Check if caller is the staker.\\n if (msg.sender != request.staker) revert CallerNotStaker();\\n\\n uint256 amount = request.queuedAmount;\\n delete (request.queuedAmount);\\n\\n emit StakeRequestCancelledFromQueue(depositKey, request.staker, amount);\\n\\n tbtcToken.safeTransfer(request.staker, amount);\\n }\\n\\n /// @notice Updates the depositor fee divisor.\\n /// @param newDepositorFeeDivisor New depositor fee divisor value.\\n function updateDepositorFeeDivisor(\\n uint64 newDepositorFeeDivisor\\n ) external onlyOwner {\\n // TODO: Introduce a parameters update process.\\n depositorFeeDivisor = newDepositorFeeDivisor;\\n\\n emit DepositorFeeDivisorUpdated(newDepositorFeeDivisor);\\n }\\n\\n // TODO: Handle minimum deposit amount in tBTC Bridge vs stBTC.\\n\\n /// @notice Encodes staker address and referral as extra data.\\n /// @dev Packs the data to bytes32: 20 bytes of staker address and\\n /// 2 bytes of referral, 10 bytes of trailing zeros.\\n /// @param staker The address to which the stBTC shares will be minted.\\n /// @param referral Data used for referral program.\\n /// @return Encoded extra data.\\n function encodeExtraData(\\n address staker,\\n uint16 referral\\n ) public pure returns (bytes32) {\\n return bytes32(abi.encodePacked(staker, referral));\\n }\\n\\n /// @notice Decodes staker address and referral from extra data.\\n /// @dev Unpacks the data from bytes32: 20 bytes of staker address and\\n /// 2 bytes of referral, 10 bytes of trailing zeros.\\n /// @param extraData Encoded extra data.\\n /// @return staker The address to which the stBTC shares will be minted.\\n /// @return referral Data used for referral program.\\n function decodeExtraData(\\n bytes32 extraData\\n ) public pure returns (address staker, uint16 referral) {\\n // First 20 bytes of extra data is staker address.\\n staker = address(uint160(bytes20(extraData)));\\n // Next 2 bytes of extra data is referral info.\\n referral = uint16(bytes2(extraData << (8 * 20)));\\n }\\n\\n /// @notice This function is used for state transitions. It ensures the current\\n /// stakte matches expected, and updates the stake request to a new\\n /// state.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param expectedState Expected current stake request state.\\n /// @param newState New stake request state.\\n function transitionStakeRequestState(\\n uint256 depositKey,\\n StakeRequestState expectedState,\\n StakeRequestState newState\\n ) internal {\\n // Validate current stake request state.\\n if (stakeRequests[depositKey].state != expectedState)\\n revert UnexpectedStakeRequestState(\\n stakeRequests[depositKey].state,\\n expectedState\\n );\\n\\n // Transition to a new state.\\n stakeRequests[depositKey].state = newState;\\n }\\n\\n /// @notice This function should be called for previously initialized stake\\n /// request, after tBTC minting process completed, meaning tBTC was\\n /// minted to this contract.\\n /// @dev It calculates the amount to stake based on the approximate minted\\n /// tBTC amount reduced by the depositor fee.\\n /// @dev IMPORTANT NOTE: The minted tBTC amount used by this function is an\\n /// approximation. See documentation of the\\n /// {{AbstractTBTCDepositor#_calculateTbtcAmount}} responsible for calculating\\n /// this value for more details.\\n /// @dev In case balance of tBTC tokens in this contract doesn't meet the\\n /// calculated tBTC amount, the function reverts with `InsufficientTbtcBalance`\\n /// error. This case requires Governance's validation, as tBTC Bridge minting\\n /// fees might changed in the way that reserve mentioned in\\n /// {{AbstractTBTCDepositor#_calculateTbtcAmount}} needs a top-up.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @return amountToStake tBTC token amount to stake after deducting tBTC bridging\\n /// fees and the depositor fee.\\n /// @return staker The address to which the stBTC shares will be minted.\\n function finalizeBridging(\\n uint256 depositKey\\n ) internal returns (uint256, address) {\\n (\\n uint256 initialDepositAmount,\\n uint256 tbtcAmount,\\n bytes32 extraData\\n ) = _finalizeDeposit(depositKey);\\n\\n // Check if current balance is sufficient to finalize bridging of `tbtcAmount`.\\n uint256 currentBalance = tbtcToken.balanceOf(address(this));\\n if (tbtcAmount > tbtcToken.balanceOf(address(this))) {\\n revert InsufficientTbtcBalance(tbtcAmount, currentBalance);\\n }\\n\\n // Compute depositor fee. The fee is calculated based on the initial funding\\n // transaction amount, before the tBTC protocol network fees were taken.\\n uint256 depositorFee = depositorFeeDivisor > 0\\n ? (initialDepositAmount / depositorFeeDivisor)\\n : 0;\\n\\n // Ensure the depositor fee does not exceed the approximate minted tBTC\\n // amount.\\n if (depositorFee >= tbtcAmount) {\\n revert DepositorFeeExceedsBridgedAmount(depositorFee, tbtcAmount);\\n }\\n\\n uint256 amountToStake = tbtcAmount - depositorFee;\\n\\n (address staker, uint16 referral) = decodeExtraData(extraData);\\n\\n // Emit event for accounting purposes to track partner's referral ID and\\n // depositor fee taken.\\n emit BridgingCompleted(\\n depositKey,\\n msg.sender,\\n referral,\\n tbtcAmount,\\n depositorFee\\n );\\n\\n // Transfer depositor fee to the treasury wallet.\\n if (depositorFee > 0) {\\n tbtcToken.safeTransfer(stbtc.treasury(), depositorFee);\\n }\\n\\n return (amountToStake, staker);\\n }\\n}\\n\",\"keccak256\":\"0x35f811a27cfb344b8153534c7e72388516e11de67f67179c467da0ad6c711711\",\"license\":\"GPL-3.0-only\"},\"contracts/Dispatcher.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/access/Ownable2Step.sol\\\";\\nimport \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport \\\"@openzeppelin/contracts/interfaces/IERC4626.sol\\\";\\nimport \\\"./Router.sol\\\";\\nimport \\\"./stBTC.sol\\\";\\n\\n/// @title Dispatcher\\n/// @notice Dispatcher is a contract that routes tBTC from stBTC to\\n/// yield vaults and back. Vaults supply yield strategies with tBTC that\\n/// generate yield for Bitcoin holders.\\ncontract Dispatcher is Router, Ownable2Step {\\n using SafeERC20 for IERC20;\\n\\n /// Struct holds information about a vault.\\n struct VaultInfo {\\n bool authorized;\\n }\\n\\n /// The main stBTC contract holding tBTC deposited by stakers.\\n stBTC public immutable stbtc;\\n /// tBTC token contract.\\n IERC20 public immutable tbtc;\\n /// Address of the maintainer bot.\\n address public maintainer;\\n\\n /// Authorized Yield Vaults that implement ERC4626 standard. These\\n /// vaults deposit assets to yield strategies, e.g. Uniswap V3\\n /// WBTC/TBTC pool. Vault can be a part of Acre ecosystem or can be\\n /// implemented externally. As long as it complies with ERC4626\\n /// standard and is authorized by the owner it can be plugged into\\n /// Acre.\\n address[] public vaults;\\n /// Mapping of vaults to their information.\\n mapping(address => VaultInfo) public vaultsInfo;\\n\\n /// Emitted when a vault is authorized.\\n /// @param vault Address of the vault.\\n event VaultAuthorized(address indexed vault);\\n\\n /// Emitted when a vault is deauthorized.\\n /// @param vault Address of the vault.\\n event VaultDeauthorized(address indexed vault);\\n\\n /// Emitted when tBTC is routed to a vault.\\n /// @param vault Address of the vault.\\n /// @param amount Amount of tBTC.\\n /// @param sharesOut Amount of received shares.\\n event DepositAllocated(\\n address indexed vault,\\n uint256 amount,\\n uint256 sharesOut\\n );\\n\\n /// Emitted when the maintainer address is updated.\\n /// @param maintainer Address of the new maintainer.\\n event MaintainerUpdated(address indexed maintainer);\\n\\n /// Reverts if the vault is already authorized.\\n error VaultAlreadyAuthorized();\\n\\n /// Reverts if the vault is not authorized.\\n error VaultUnauthorized();\\n\\n /// Reverts if the caller is not the maintainer.\\n error NotMaintainer();\\n\\n /// Reverts if the address is zero.\\n error ZeroAddress();\\n\\n /// Modifier that reverts if the caller is not the maintainer.\\n modifier onlyMaintainer() {\\n if (msg.sender != maintainer) {\\n revert NotMaintainer();\\n }\\n _;\\n }\\n\\n constructor(stBTC _stbtc, IERC20 _tbtc) Ownable(msg.sender) {\\n stbtc = _stbtc;\\n tbtc = _tbtc;\\n }\\n\\n /// @notice Adds a vault to the list of authorized vaults.\\n /// @param vault Address of the vault to add.\\n function authorizeVault(address vault) external onlyOwner {\\n if (isVaultAuthorized(vault)) {\\n revert VaultAlreadyAuthorized();\\n }\\n\\n vaults.push(vault);\\n vaultsInfo[vault].authorized = true;\\n\\n emit VaultAuthorized(vault);\\n }\\n\\n /// @notice Removes a vault from the list of authorized vaults.\\n /// @param vault Address of the vault to remove.\\n function deauthorizeVault(address vault) external onlyOwner {\\n if (!isVaultAuthorized(vault)) {\\n revert VaultUnauthorized();\\n }\\n\\n vaultsInfo[vault].authorized = false;\\n\\n for (uint256 i = 0; i < vaults.length; i++) {\\n if (vaults[i] == vault) {\\n vaults[i] = vaults[vaults.length - 1];\\n // slither-disable-next-line costly-loop\\n vaults.pop();\\n break;\\n }\\n }\\n\\n emit VaultDeauthorized(vault);\\n }\\n\\n /// @notice Updates the maintainer address.\\n /// @param newMaintainer Address of the new maintainer.\\n function updateMaintainer(address newMaintainer) external onlyOwner {\\n if (newMaintainer == address(0)) {\\n revert ZeroAddress();\\n }\\n\\n maintainer = newMaintainer;\\n\\n emit MaintainerUpdated(maintainer);\\n }\\n\\n /// TODO: make this function internal once the allocation distribution is\\n /// implemented\\n /// @notice Routes tBTC from stBTC to a vault. Can be called by the maintainer\\n /// only.\\n /// @param vault Address of the vault to route the assets to.\\n /// @param amount Amount of tBTC to deposit.\\n /// @param minSharesOut Minimum amount of shares to receive.\\n function depositToVault(\\n address vault,\\n uint256 amount,\\n uint256 minSharesOut\\n ) public onlyMaintainer {\\n if (!isVaultAuthorized(vault)) {\\n revert VaultUnauthorized();\\n }\\n\\n // slither-disable-next-line arbitrary-send-erc20\\n tbtc.safeTransferFrom(address(stbtc), address(this), amount);\\n tbtc.forceApprove(address(vault), amount);\\n\\n uint256 sharesOut = deposit(\\n IERC4626(vault),\\n address(stbtc),\\n amount,\\n minSharesOut\\n );\\n // slither-disable-next-line reentrancy-events\\n emit DepositAllocated(vault, amount, sharesOut);\\n }\\n\\n /// @notice Returns the list of authorized vaults.\\n function getVaults() public view returns (address[] memory) {\\n return vaults;\\n }\\n\\n /// @notice Returns true if the vault is authorized.\\n /// @param vault Address of the vault to check.\\n function isVaultAuthorized(address vault) public view returns (bool) {\\n return vaultsInfo[vault].authorized;\\n }\\n\\n /// TODO: implement redeem() / withdraw() functions\\n}\\n\",\"keccak256\":\"0x5adb54e73b82adf0befabef894d99d9bb5eb785895851764ec9f497a055ae47f\",\"license\":\"GPL-3.0-only\"},\"contracts/Router.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/interfaces/IERC4626.sol\\\";\\n\\n/// @title Router\\n/// @notice Router is a contract that routes tBTC from stBTC to\\n/// a given vault and back. Vaults supply yield strategies with tBTC that\\n/// generate yield for Bitcoin holders.\\nabstract contract Router {\\n /// Thrown when amount of shares received is below the min set by caller.\\n /// @param vault Address of the vault.\\n /// @param sharesOut Amount of received shares.\\n /// @param minSharesOut Minimum amount of shares expected to receive.\\n error MinSharesError(\\n address vault,\\n uint256 sharesOut,\\n uint256 minSharesOut\\n );\\n\\n /// @notice Routes funds from stBTC to a vault. The amount of tBTC to\\n /// Shares of deposited tBTC are minted to the stBTC contract.\\n /// @param vault Address of the vault to route the funds to.\\n /// @param receiver Address of the receiver of the shares.\\n /// @param amount Amount of tBTC to deposit.\\n /// @param minSharesOut Minimum amount of shares to receive.\\n function deposit(\\n IERC4626 vault,\\n address receiver,\\n uint256 amount,\\n uint256 minSharesOut\\n ) internal returns (uint256 sharesOut) {\\n if ((sharesOut = vault.deposit(amount, receiver)) < minSharesOut) {\\n revert MinSharesError(address(vault), sharesOut, minSharesOut);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x520e27c613f1234755c23402524b048a81abd15222d7f318504992d490248812\",\"license\":\"GPL-3.0-only\"},\"contracts/stBTC.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\\\";\\nimport \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport \\\"@openzeppelin/contracts/access/Ownable2Step.sol\\\";\\nimport \\\"./Dispatcher.sol\\\";\\n\\n/// @title stBTC\\n/// @notice This contract implements the ERC-4626 tokenized vault standard. By\\n/// staking tBTC, users acquire a liquid staking token called stBTC,\\n/// commonly referred to as \\\"shares\\\". The staked tBTC is securely\\n/// deposited into Acre's vaults, where it generates yield over time.\\n/// Users have the flexibility to redeem stBTC, enabling them to\\n/// withdraw their staked tBTC along with the accrued yield.\\n/// @dev ERC-4626 is a standard to optimize and unify the technical parameters\\n/// of yield-bearing vaults. This contract facilitates the minting and\\n/// burning of shares (stBTC), which are represented as standard ERC20\\n/// tokens, providing a seamless exchange with tBTC tokens.\\ncontract stBTC is ERC4626, Ownable2Step {\\n using SafeERC20 for IERC20;\\n\\n /// Dispatcher contract that routes tBTC from stBTC to a given vault and back.\\n Dispatcher public dispatcher;\\n\\n /// Address of the treasury wallet, where fees should be transferred to.\\n address public treasury;\\n\\n /// Minimum amount for a single deposit operation. The value should be set\\n /// low enough so the deposits routed through Bitcoin Depositor contract won't\\n /// be rejected. It means that minimumDepositAmount should be lower than\\n /// tBTC protocol's depositDustThreshold reduced by all the minting fees taken\\n /// before depositing in the Acre contract.\\n uint256 public minimumDepositAmount;\\n\\n /// Maximum total amount of tBTC token held by Acre protocol.\\n uint256 public maximumTotalAssets;\\n\\n /// Emitted when the treasury wallet address is updated.\\n /// @param treasury New treasury wallet address.\\n event TreasuryUpdated(address treasury);\\n\\n /// Emitted when deposit parameters are updated.\\n /// @param minimumDepositAmount New value of the minimum deposit amount.\\n /// @param maximumTotalAssets New value of the maximum total assets amount.\\n event DepositParametersUpdated(\\n uint256 minimumDepositAmount,\\n uint256 maximumTotalAssets\\n );\\n\\n /// Emitted when the dispatcher contract is updated.\\n /// @param oldDispatcher Address of the old dispatcher contract.\\n /// @param newDispatcher Address of the new dispatcher contract.\\n event DispatcherUpdated(address oldDispatcher, address newDispatcher);\\n\\n /// Reverts if the amount is less than the minimum deposit amount.\\n /// @param amount Amount to check.\\n /// @param min Minimum amount to check 'amount' against.\\n error LessThanMinDeposit(uint256 amount, uint256 min);\\n\\n /// Reverts if the address is zero.\\n error ZeroAddress();\\n\\n /// Reverts if the address is disallowed.\\n error DisallowedAddress();\\n\\n constructor(\\n IERC20 _tbtc,\\n address _treasury\\n ) ERC4626(_tbtc) ERC20(\\\"Acre Staked Bitcoin\\\", \\\"stBTC\\\") Ownable(msg.sender) {\\n if (address(_treasury) == address(0)) {\\n revert ZeroAddress();\\n }\\n treasury = _treasury;\\n // TODO: Revisit the exact values closer to the launch.\\n minimumDepositAmount = 0.001 * 1e18; // 0.001 tBTC\\n maximumTotalAssets = 25 * 1e18; // 25 tBTC\\n }\\n\\n /// @notice Updates treasury wallet address.\\n /// @param newTreasury New treasury wallet address.\\n function updateTreasury(address newTreasury) external onlyOwner {\\n // TODO: Introduce a parameters update process.\\n if (newTreasury == address(0)) {\\n revert ZeroAddress();\\n }\\n if (newTreasury == address(this)) {\\n revert DisallowedAddress();\\n }\\n treasury = newTreasury;\\n\\n emit TreasuryUpdated(newTreasury);\\n }\\n\\n /// @notice Updates deposit parameters.\\n /// @dev To disable the limit for deposits, set the maximum total assets to\\n /// maximum (`type(uint256).max`).\\n /// @param _minimumDepositAmount New value of the minimum deposit amount. It\\n /// is the minimum amount for a single deposit operation.\\n /// @param _maximumTotalAssets New value of the maximum total assets amount.\\n /// It is the maximum amount of the tBTC token that the Acre protocol\\n /// can hold.\\n function updateDepositParameters(\\n uint256 _minimumDepositAmount,\\n uint256 _maximumTotalAssets\\n ) external onlyOwner {\\n // TODO: Introduce a parameters update process.\\n minimumDepositAmount = _minimumDepositAmount;\\n maximumTotalAssets = _maximumTotalAssets;\\n\\n emit DepositParametersUpdated(\\n _minimumDepositAmount,\\n _maximumTotalAssets\\n );\\n }\\n\\n // TODO: Implement a governed upgrade process that initiates an update and\\n // then finalizes it after a delay.\\n /// @notice Updates the dispatcher contract and gives it an unlimited\\n /// allowance to transfer staked tBTC.\\n /// @param newDispatcher Address of the new dispatcher contract.\\n function updateDispatcher(Dispatcher newDispatcher) external onlyOwner {\\n if (address(newDispatcher) == address(0)) {\\n revert ZeroAddress();\\n }\\n\\n address oldDispatcher = address(dispatcher);\\n\\n emit DispatcherUpdated(oldDispatcher, address(newDispatcher));\\n dispatcher = newDispatcher;\\n\\n // TODO: Once withdrawal/rebalancing is implemented, we need to revoke the\\n // approval of the vaults share tokens from the old dispatcher and approve\\n // a new dispatcher to manage the share tokens.\\n\\n if (oldDispatcher != address(0)) {\\n // Setting allowance to zero for the old dispatcher\\n IERC20(asset()).forceApprove(oldDispatcher, 0);\\n }\\n\\n // Setting allowance to max for the new dispatcher\\n IERC20(asset()).forceApprove(address(dispatcher), type(uint256).max);\\n }\\n\\n /// @notice Mints shares to receiver by depositing exactly amount of\\n /// tBTC tokens.\\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\\n /// which determines the minimum amount for a single deposit operation.\\n /// The amount of the assets has to be pre-approved in the tBTC\\n /// contract.\\n /// @param assets Approved amount of tBTC tokens to deposit.\\n /// @param receiver The address to which the shares will be minted.\\n /// @return Minted shares.\\n function deposit(\\n uint256 assets,\\n address receiver\\n ) public override returns (uint256) {\\n if (assets < minimumDepositAmount) {\\n revert LessThanMinDeposit(assets, minimumDepositAmount);\\n }\\n\\n return super.deposit(assets, receiver);\\n }\\n\\n /// @notice Mints shares to receiver by depositing tBTC tokens.\\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\\n /// which determines the minimum amount for a single deposit operation.\\n /// The amount of the assets has to be pre-approved in the tBTC\\n /// contract.\\n /// The msg.sender is required to grant approval for tBTC transfer.\\n /// To determine the total assets amount necessary for approval\\n /// corresponding to a given share amount, use the `previewMint` function.\\n /// @param shares Amount of shares to mint.\\n /// @param receiver The address to which the shares will be minted.\\n function mint(\\n uint256 shares,\\n address receiver\\n ) public override returns (uint256 assets) {\\n if ((assets = super.mint(shares, receiver)) < minimumDepositAmount) {\\n revert LessThanMinDeposit(assets, minimumDepositAmount);\\n }\\n }\\n\\n /// @notice Returns value of assets that would be exchanged for the amount of\\n /// shares owned by the `account`.\\n /// @param account Owner of shares.\\n /// @return Assets amount.\\n function assetsBalanceOf(address account) public view returns (uint256) {\\n return convertToAssets(balanceOf(account));\\n }\\n\\n /// @notice Returns the maximum amount of the tBTC token that can be\\n /// deposited into the vault for the receiver through a deposit\\n /// call. It takes into account the deposit parameter, maximum total\\n /// assets, which determines the total amount of tBTC token held by\\n /// Acre protocol.\\n /// @dev When the remaining amount of unused limit is less than the minimum\\n /// deposit amount, this function returns 0.\\n /// @return The maximum amount of tBTC token that can be deposited into\\n /// Acre protocol for the receiver.\\n function maxDeposit(address) public view override returns (uint256) {\\n if (maximumTotalAssets == type(uint256).max) {\\n return type(uint256).max;\\n }\\n\\n uint256 _totalAssets = totalAssets();\\n\\n return\\n _totalAssets >= maximumTotalAssets\\n ? 0\\n : maximumTotalAssets - _totalAssets;\\n }\\n\\n /// @notice Returns the maximum amount of the vault shares that can be\\n /// minted for the receiver, through a mint call.\\n /// @dev Since the stBTC contract limits the maximum total tBTC tokens this\\n /// function converts the maximum deposit amount to shares.\\n /// @return The maximum amount of the vault shares.\\n function maxMint(address receiver) public view override returns (uint256) {\\n uint256 _maxDeposit = maxDeposit(receiver);\\n\\n // slither-disable-next-line incorrect-equality\\n return\\n _maxDeposit == type(uint256).max\\n ? type(uint256).max\\n : convertToShares(_maxDeposit);\\n }\\n\\n /// @return Returns deposit parameters.\\n function depositParameters() public view returns (uint256, uint256) {\\n return (minimumDepositAmount, maximumTotalAssets);\\n }\\n}\\n\",\"keccak256\":\"0x6d980629590d39aa0c1acb2f38c1f100ef08e976cd67ba76c6f99b07ed43865b\",\"license\":\"GPL-3.0-only\"}},\"version\":1}", - "bytecode": "0x60806040523480156200001157600080fd5b506040516200249b3803806200249b8339810160408190526200003491620002f4565b33806200005c57604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b620000678162000106565b5062000074848462000124565b6001600160a01b0382166200009c5760405163182b2a8160e21b815260040160405180910390fd5b6001600160a01b038116620000c45760405163e4ee787760e01b815260040160405180910390fd5b603480546001600160a01b0319166001600160a01b0393841617905560358054919092166001600160e01b031990911617607d60a31b17905550620003519050565b603280546001600160a01b0319169055620001218162000285565b50565b6000546001600160a01b03161580156200014757506001546001600160a01b0316155b620001a75760405162461bcd60e51b815260206004820152602960248201527f4162737472616374544254434465706f7369746f7220616c726561647920696e6044820152681a5d1a585b1a5e995960ba1b606482015260840162000053565b6001600160a01b038216620001ff5760405162461bcd60e51b815260206004820152601d60248201527f42726964676520616464726573732063616e6e6f74206265207a65726f000000604482015260640162000053565b6001600160a01b038116620002575760405162461bcd60e51b815260206004820181905260248201527f544254435661756c7420616464726573732063616e6e6f74206265207a65726f604482015260640162000053565b600080546001600160a01b039384166001600160a01b03199182161790915560018054929093169116179055565b603180546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b80516001600160a01b0381168114620002ef57600080fd5b919050565b600080600080608085870312156200030b57600080fd5b6200031685620002d7565b93506200032660208601620002d7565b92506200033660408601620002d7565b91506200034660608601620002d7565b905092959194509250565b61213a80620003616000396000f3fe608060405234801561001057600080fd5b506004361061016c5760003560e01c8063c143d675116100cd578063da9ad53c11610081578063e5d3d71411610066578063e5d3d71414610355578063e78cea9214610368578063f2fde38b1461037b57600080fd5b8063da9ad53c14610331578063e30c39781461034457600080fd5b8063c9f5a5d8116100b2578063c9f5a5d8146102b4578063d0714ad5146102c7578063d990d3ff1461031e57600080fd5b8063c143d67514610274578063c7ba0347146102a857600080fd5b8063774e2e90116101245780638da5cb5b116101095780638da5cb5b1461023d5780639bef6d521461024e578063b2e665bf1461026157600080fd5b8063774e2e90146101f257806379ba50971461023557600080fd5b80633d11a6ae116101555780633d11a6ae146101b657806369e1df8b146101d7578063715018a6146101ea57600080fd5b80630f36403a146101715780633647b205146101a1575b600080fd5b600154610184906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b6101b46101af366004611977565b61038e565b005b6101c96101c43660046119cb565b61040c565b604051908152602001610198565b6101b46101e5366004611a00565b61047b565b6101b461055a565b610213610200366004611a00565b606081901c9160509190911c61ffff1690565b604080516001600160a01b03909316835261ffff909116602083015201610198565b6101b461056e565b6031546001600160a01b0316610184565b603554610184906001600160a01b031681565b6101b461026f366004611a00565b6105b7565b60355461028f90600160a01b900467ffffffffffffffff1681565b60405167ffffffffffffffff9091168152602001610198565b6101c96402540be40081565b6101b46102c2366004611a00565b610714565b61030f6102d5366004611a00565b60336020526000908152604090205460ff81169061010081046001600160a01b031690600160a81b90046affffffffffffffffffffff1683565b60405161019893929190611a51565b6101b461032c366004611a89565b61084e565b6101b461033f366004611a00565b6108f2565b6032546001600160a01b0316610184565b603454610184906001600160a01b031681565b600054610184906001600160a01b031681565b6101b4610389366004611b0d565b6109a9565b610396610a27565b603580547fffffffff0000000000000000ffffffffffffffffffffffffffffffffffffffff16600160a01b67ffffffffffffffff8416908102919091179091556040519081527f53a618edd6eab9ce346f438670ebd45da60fa3d85662375fae2b8beadf08faf39060200160405180910390a150565b6040516bffffffffffffffffffffffff19606084901b1660208201527fffff00000000000000000000000000000000000000000000000000000000000060f083901b16603482015260009060360160405160208183030381529060405261047290611b2a565b90505b92915050565b6104888160016003610a54565b6000818152603360205260408120906104a083610b0b565b83546001600160a01b03909116610100027fffffffffffffffffffffff0000000000000000000000000000000000000000ff90911617835590506104e381610dd7565b825474ffffffffffffffffffffffffffffffffffffffffff16600160a81b6affffffffffffffffffffff9283168102919091178085556040519190049091168152339084907ff412c1941036889a8a2aec22dca20565f685239ac78976dab58b52eb70f972fa9060200160405180910390a3505050565b610562610a27565b61056c6000610e2c565b565b60325433906001600160a01b031681146105ab5760405163118cdaa760e01b81526001600160a01b03821660048201526024015b60405180910390fd5b6105b481610e2c565b50565b6105c48160036004610a54565b600081815260336020526040812080549091600160a81b9091046affffffffffffffffffffff16900361060a57604051632145277d60e21b815260040160405180910390fd5b805474ffffffffffffffffffffffffffffffffffffffffff81168255604051600160a81b9091046affffffffffffffffffffff1680825290339084907ff0a477d0ba7b549d19236a4c6517edef5574c03ed185bad57c92c9323091af8f9060200160405180910390a3603554603454610690916001600160a01b03918216911683610e52565b6035548254604051636e553f6560e01b8152600481018490526001600160a01b0361010090920482166024820152911690636e553f65906044015b6020604051808303816000875af11580156106ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061070e9190611b51565b50505050565b6107218160036005610a54565b600081815260336020526040812080549091600160a81b9091046affffffffffffffffffffff16900361076757604051632145277d60e21b815260040160405180910390fd5b805461010090046001600160a01b031633146107af576040517f709d46f200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b805474ffffffffffffffffffffffffffffffffffffffffff8116808355604051600160a81b9092046affffffffffffffffffffff16808352916101009091046001600160a01b03169084907f32aa57d54fb0ee2c9617ac9d5982ba7d88869fcbf89542a285d6c07b03dc504e9060200160405180910390a38154603454610849916001600160a01b03918216916101009091041683610ef5565b505050565b6001600160a01b03821661088e576040517ff606bf2a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006108a4858561089f868661040c565b610f69565b90506108b38160006001610a54565b6040516001600160a01b03841690339083907f8d019883471b734b0033fe25a5b76c3afefbbfa9e9b3dacdbabf505b9e4f455d90600090a45050505050565b6108ff8160016002610a54565b60008061090b83610b0b565b91509150336001600160a01b0316837f2b57d79a66895fd41ae6d27049952259b0d40a9b7c563a99b3f1844b288da08c8460405161094b91815260200190565b60405180910390a3603554603454610970916001600160a01b03918216911684610e52565b603554604051636e553f6560e01b8152600481018490526001600160a01b03838116602483015290911690636e553f65906044016106cb565b6109b1610a27565b603280546001600160a01b03831673ffffffffffffffffffffffffffffffffffffffff1990911681179091556109ef6031546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b6031546001600160a01b0316331461056c5760405163118cdaa760e01b81523360048201526024016105a2565b816005811115610a6657610a66611a19565b60008481526033602052604090205460ff166005811115610a8957610a89611a19565b14610ad657600083815260336020526040908190205490517fbcbf502b0000000000000000000000000000000000000000000000000000000081526105a29160ff16908490600401611b6a565b6000838152603360205260409020805482919060ff19166001836005811115610b0157610b01611a19565b0217905550505050565b6000806000806000610b1c866110c6565b6034546040516370a0823160e01b815230600482015293965091945092506000916001600160a01b03909116906370a0823190602401602060405180830381865afa158015610b6f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b939190611b51565b6034546040516370a0823160e01b81523060048201529192506001600160a01b0316906370a0823190602401602060405180830381865afa158015610bdc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c009190611b51565b831115610c43576040517fcad48b6900000000000000000000000000000000000000000000000000000000815260048101849052602481018290526044016105a2565b603554600090600160a01b900467ffffffffffffffff16610c65576000610c83565b603554610c8390600160a01b900467ffffffffffffffff1686611b9b565b9050838110610cc8576040517f2395edf200000000000000000000000000000000000000000000000000000000815260048101829052602481018590526044016105a2565b6000610cd48286611bbd565b6040805187815260208101859052919250606086901c9161ffff605088901c1691829133918e917f6410e64d304208a5e90fc76ab4fbf4e7b8836705daeda8dde27611ae0524490a910160405180910390a48315610dc757603554604080517f61d027b30000000000000000000000000000000000000000000000000000000081529051610dc7926001600160a01b0316916361d027b39160048083019260209291908290030181865afa158015610d90573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610db49190611bdb565b6034546001600160a01b03169086610ef5565b5090999098509650505050505050565b60006affffffffffffffffffffff821115610e28576040517f6dfcc65000000000000000000000000000000000000000000000000000000000815260586004820152602481018390526044016105a2565b5090565b6032805473ffffffffffffffffffffffffffffffffffffffff191690556105b481611350565b6040517fdd62ed3e0000000000000000000000000000000000000000000000000000000081523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015610ebb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610edf9190611b51565b905061070e8484610ef08585611bf8565b6113af565b6040516001600160a01b0383811660248301526044820183905261084991859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050611469565b6001546000906001600160a01b0316610f8860c0850160a08601611b0d565b6001600160a01b031614610fde5760405162461bcd60e51b815260206004820152601660248201527f5661756c742061646472657373206d69736d617463680000000000000000000060448201526064016105a2565b6000610ffe610fec866114e5565b610ff96020870187611c1d565b61154a565b60405163ffffffff4216815290915081907fa3ed7aef0745e1a91addae9e5daee7a8ace74852fec840b9d93da747855dd7b99060200160405180910390a26000546040517f86f014390000000000000000000000000000000000000000000000000000000081526001600160a01b03909116906386f014399061108990889088908890600401611ce5565b600060405180830381600087803b1580156110a357600080fd5b505af11580156110b7573d6000803e3d6000fd5b509293505050505b9392505050565b600080546040517fb02c43d0000000000000000000000000000000000000000000000000000000008152600481018490528291829182916001600160a01b03169063b02c43d09060240160e060405180830381865afa15801561112d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111519190611e60565b9050806040015163ffffffff166000036111ad5760405162461bcd60e51b815260206004820152601760248201527f4465706f736974206e6f7420696e697469616c697a656400000000000000000060448201526064016105a2565b6001546040517f6c626aa4000000000000000000000000000000000000000000000000000000008152600481018790526000916001600160a01b031690636c626aa49060240160408051808303816000875af1158015611211573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112359190611f1a565b9150508160a0015163ffffffff16600014158061125b575067ffffffffffffffff811615155b6112cd5760405162461bcd60e51b815260206004820152602360248201527f4465706f736974206e6f742066696e616c697a6564206279207468652062726960448201527f646765000000000000000000000000000000000000000000000000000000000060648201526084016105a2565b6402540be400826020015167ffffffffffffffff166112ec9190611f54565b945061130082602001518360800151611594565b6040805182815263ffffffff4216602082015291955087917f417b6288c9f637614f8b3f7a275fb4e44e517930fde949e463d58dfe0b97f28b910160405180910390a25060c00151929491935050565b603180546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f095ea7b30000000000000000000000000000000000000000000000000000000017905261142e8482611717565b61070e576040516001600160a01b0384811660248301526000604483015261146391869182169063095ea7b390606401610f22565b61070e84825b600061147e6001600160a01b038416836117bf565b905080516000141580156114a35750808060200190518101906114a19190611f6b565b155b15610849576040517f5274afe70000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024016105a2565b60006104756114f76020840184611f8d565b6115046020850185611fa8565b6115116040870187611fa8565b6115216080890160608a01611f8d565b60405160200161153696959493929190611fef565b6040516020818303038152906040526117cd565b6000828260405160200161157592919091825260e01b6001600160e01b031916602082015260240190565b60408051601f1981840301815291905280516020909101209392505050565b6000806402540be4006115a78486612031565b67ffffffffffffffff166115bb9190611f54565b90506000600160009054906101000a90046001600160a01b03166001600160a01b03166309b53f516040518163ffffffff1660e01b8152600401602060405180830381865afa158015611612573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116369190612059565b63ffffffff169050600080821161164e576000611658565b6116588284611b9b565b905060008060009054906101000a90046001600160a01b03166001600160a01b031663c42b64d06040518163ffffffff1660e01b8152600401608060405180830381865afa1580156116ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116d29190612076565b509250505060006402540be4008267ffffffffffffffff166116f49190611f54565b9050806117018487611bbd565b61170b9190611bbd565b98975050505050505050565b6000806000846001600160a01b03168460405161173491906120d5565b6000604051808303816000865af19150503d8060008114611771576040519150601f19603f3d011682016040523d82523d6000602084013e611776565b606091505b50915091508180156117a05750805115806117a05750808060200190518101906117a09190611f6b565b80156117b657506000856001600160a01b03163b115b95945050505050565b6060610472838360006117f4565b60006020600083516020850160025afa50602060006020600060025afa5050600051919050565b606081471015611832576040517fcd7860590000000000000000000000000000000000000000000000000000000081523060048201526024016105a2565b600080856001600160a01b0316848660405161184e91906120d5565b60006040518083038185875af1925050503d806000811461188b576040519150601f19603f3d011682016040523d82523d6000602084013e611890565b606091505b50915091506118a08683836118aa565b9695505050505050565b6060826118bf576118ba8261191f565b6110bf565b81511580156118d657506001600160a01b0384163b155b15611918576040517f9996b3150000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024016105a2565b50806110bf565b80511561192f5780518082602001fd5b6040517f1425ea4200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b67ffffffffffffffff811681146105b457600080fd5b60006020828403121561198957600080fd5b81356110bf81611961565b6001600160a01b03811681146105b457600080fd5b80356119b481611994565b919050565b803561ffff811681146119b457600080fd5b600080604083850312156119de57600080fd5b82356119e981611994565b91506119f7602084016119b9565b90509250929050565b600060208284031215611a1257600080fd5b5035919050565b634e487b7160e01b600052602160045260246000fd5b60068110611a4d57634e487b7160e01b600052602160045260246000fd5b9052565b60608101611a5f8286611a2f565b6001600160a01b03841660208301526affffffffffffffffffffff83166040830152949350505050565b600080600080848603610120811215611aa157600080fd5b853567ffffffffffffffff811115611ab857600080fd5b860160808189031215611aca57600080fd5b945060c0601f1982011215611ade57600080fd5b5060208501925060e0850135611af381611994565b9150611b0261010086016119b9565b905092959194509250565b600060208284031215611b1f57600080fd5b81356110bf81611994565b80516020808301519190811015611b4b576000198160200360031b1b821691505b50919050565b600060208284031215611b6357600080fd5b5051919050565b60408101611b788285611a2f565b6110bf6020830184611a2f565b634e487b7160e01b600052601160045260246000fd5b600082611bb857634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561047557610475611b85565b80516119b481611994565b600060208284031215611bed57600080fd5b81516110bf81611994565b8082018082111561047557610475611b85565b63ffffffff811681146105b457600080fd5b600060208284031215611c2f57600080fd5b81356110bf81611c0b565b80356001600160e01b0319811681146119b457600080fd5b6000808335601e19843603018112611c6957600080fd5b830160208101925035905067ffffffffffffffff811115611c8957600080fd5b803603821315611c9857600080fd5b9250929050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b80356bffffffffffffffffffffffff19811681146119b457600080fd5b60006101008083526001600160e01b031980611d0088611c3a565b1682850152611d126020880188611c52565b92506080610120860152611d2b61018086018483611c9f565b925050611d3b6040880188611c52565b85840360ff1901610140870152611d53848284611c9f565b9350505080611d6460608901611c3a565b166101608501525090508335611d7981611c0b565b63ffffffff811660208401525060208401357fffffffffffffffff0000000000000000000000000000000000000000000000008116808214611dba57600080fd5b80604085015250506bffffffffffffffffffffffff19611ddc60408601611cc8565b166060830152611dee60608501611cc8565b6bffffffffffffffffffffffff198116608084015250611e1060808501611c3a565b6001600160e01b0319811660a084015250611e2d60a085016119a9565b6001600160a01b031660c083015260e09091019190915292915050565b80516119b481611961565b80516119b481611c0b565b600060e08284031215611e7257600080fd5b60405160e0810181811067ffffffffffffffff82111715611ea357634e487b7160e01b600052604160045260246000fd5b604052611eaf83611bd0565b8152611ebd60208401611e4a565b6020820152611ece60408401611e55565b6040820152611edf60608401611bd0565b6060820152611ef060808401611e4a565b6080820152611f0160a08401611e55565b60a082015260c083015160c08201528091505092915050565b60008060408385031215611f2d57600080fd5b8251611f3881611961565b6020840151909250611f4981611961565b809150509250929050565b808202811582820484141761047557610475611b85565b600060208284031215611f7d57600080fd5b815180151581146110bf57600080fd5b600060208284031215611f9f57600080fd5b61047282611c3a565b6000808335601e19843603018112611fbf57600080fd5b83018035915067ffffffffffffffff821115611fda57600080fd5b602001915036819003821315611c9857600080fd5b60006001600160e01b03198089168352868860048501378683016004810160008152868882375093169390920160048101939093525050600801949350505050565b67ffffffffffffffff82811682821603908082111561205257612052611b85565b5092915050565b60006020828403121561206b57600080fd5b81516110bf81611c0b565b6000806000806080858703121561208c57600080fd5b845161209781611961565b60208601519094506120a881611961565b60408601519093506120b981611961565b60608601519092506120ca81611c0b565b939692955090935050565b6000825160005b818110156120f657602081860181015185830152016120dc565b50600092019182525091905056fea2646970667358221220462bf22e2a3e5c424c7897cc702ca2994745ded2b209ca480d6b59b6977ef88a64736f6c63430008150033", - "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061016c5760003560e01c8063c143d675116100cd578063da9ad53c11610081578063e5d3d71411610066578063e5d3d71414610355578063e78cea9214610368578063f2fde38b1461037b57600080fd5b8063da9ad53c14610331578063e30c39781461034457600080fd5b8063c9f5a5d8116100b2578063c9f5a5d8146102b4578063d0714ad5146102c7578063d990d3ff1461031e57600080fd5b8063c143d67514610274578063c7ba0347146102a857600080fd5b8063774e2e90116101245780638da5cb5b116101095780638da5cb5b1461023d5780639bef6d521461024e578063b2e665bf1461026157600080fd5b8063774e2e90146101f257806379ba50971461023557600080fd5b80633d11a6ae116101555780633d11a6ae146101b657806369e1df8b146101d7578063715018a6146101ea57600080fd5b80630f36403a146101715780633647b205146101a1575b600080fd5b600154610184906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b6101b46101af366004611977565b61038e565b005b6101c96101c43660046119cb565b61040c565b604051908152602001610198565b6101b46101e5366004611a00565b61047b565b6101b461055a565b610213610200366004611a00565b606081901c9160509190911c61ffff1690565b604080516001600160a01b03909316835261ffff909116602083015201610198565b6101b461056e565b6031546001600160a01b0316610184565b603554610184906001600160a01b031681565b6101b461026f366004611a00565b6105b7565b60355461028f90600160a01b900467ffffffffffffffff1681565b60405167ffffffffffffffff9091168152602001610198565b6101c96402540be40081565b6101b46102c2366004611a00565b610714565b61030f6102d5366004611a00565b60336020526000908152604090205460ff81169061010081046001600160a01b031690600160a81b90046affffffffffffffffffffff1683565b60405161019893929190611a51565b6101b461032c366004611a89565b61084e565b6101b461033f366004611a00565b6108f2565b6032546001600160a01b0316610184565b603454610184906001600160a01b031681565b600054610184906001600160a01b031681565b6101b4610389366004611b0d565b6109a9565b610396610a27565b603580547fffffffff0000000000000000ffffffffffffffffffffffffffffffffffffffff16600160a01b67ffffffffffffffff8416908102919091179091556040519081527f53a618edd6eab9ce346f438670ebd45da60fa3d85662375fae2b8beadf08faf39060200160405180910390a150565b6040516bffffffffffffffffffffffff19606084901b1660208201527fffff00000000000000000000000000000000000000000000000000000000000060f083901b16603482015260009060360160405160208183030381529060405261047290611b2a565b90505b92915050565b6104888160016003610a54565b6000818152603360205260408120906104a083610b0b565b83546001600160a01b03909116610100027fffffffffffffffffffffff0000000000000000000000000000000000000000ff90911617835590506104e381610dd7565b825474ffffffffffffffffffffffffffffffffffffffffff16600160a81b6affffffffffffffffffffff9283168102919091178085556040519190049091168152339084907ff412c1941036889a8a2aec22dca20565f685239ac78976dab58b52eb70f972fa9060200160405180910390a3505050565b610562610a27565b61056c6000610e2c565b565b60325433906001600160a01b031681146105ab5760405163118cdaa760e01b81526001600160a01b03821660048201526024015b60405180910390fd5b6105b481610e2c565b50565b6105c48160036004610a54565b600081815260336020526040812080549091600160a81b9091046affffffffffffffffffffff16900361060a57604051632145277d60e21b815260040160405180910390fd5b805474ffffffffffffffffffffffffffffffffffffffffff81168255604051600160a81b9091046affffffffffffffffffffff1680825290339084907ff0a477d0ba7b549d19236a4c6517edef5574c03ed185bad57c92c9323091af8f9060200160405180910390a3603554603454610690916001600160a01b03918216911683610e52565b6035548254604051636e553f6560e01b8152600481018490526001600160a01b0361010090920482166024820152911690636e553f65906044015b6020604051808303816000875af11580156106ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061070e9190611b51565b50505050565b6107218160036005610a54565b600081815260336020526040812080549091600160a81b9091046affffffffffffffffffffff16900361076757604051632145277d60e21b815260040160405180910390fd5b805461010090046001600160a01b031633146107af576040517f709d46f200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b805474ffffffffffffffffffffffffffffffffffffffffff8116808355604051600160a81b9092046affffffffffffffffffffff16808352916101009091046001600160a01b03169084907f32aa57d54fb0ee2c9617ac9d5982ba7d88869fcbf89542a285d6c07b03dc504e9060200160405180910390a38154603454610849916001600160a01b03918216916101009091041683610ef5565b505050565b6001600160a01b03821661088e576040517ff606bf2a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006108a4858561089f868661040c565b610f69565b90506108b38160006001610a54565b6040516001600160a01b03841690339083907f8d019883471b734b0033fe25a5b76c3afefbbfa9e9b3dacdbabf505b9e4f455d90600090a45050505050565b6108ff8160016002610a54565b60008061090b83610b0b565b91509150336001600160a01b0316837f2b57d79a66895fd41ae6d27049952259b0d40a9b7c563a99b3f1844b288da08c8460405161094b91815260200190565b60405180910390a3603554603454610970916001600160a01b03918216911684610e52565b603554604051636e553f6560e01b8152600481018490526001600160a01b03838116602483015290911690636e553f65906044016106cb565b6109b1610a27565b603280546001600160a01b03831673ffffffffffffffffffffffffffffffffffffffff1990911681179091556109ef6031546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b6031546001600160a01b0316331461056c5760405163118cdaa760e01b81523360048201526024016105a2565b816005811115610a6657610a66611a19565b60008481526033602052604090205460ff166005811115610a8957610a89611a19565b14610ad657600083815260336020526040908190205490517fbcbf502b0000000000000000000000000000000000000000000000000000000081526105a29160ff16908490600401611b6a565b6000838152603360205260409020805482919060ff19166001836005811115610b0157610b01611a19565b0217905550505050565b6000806000806000610b1c866110c6565b6034546040516370a0823160e01b815230600482015293965091945092506000916001600160a01b03909116906370a0823190602401602060405180830381865afa158015610b6f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b939190611b51565b6034546040516370a0823160e01b81523060048201529192506001600160a01b0316906370a0823190602401602060405180830381865afa158015610bdc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c009190611b51565b831115610c43576040517fcad48b6900000000000000000000000000000000000000000000000000000000815260048101849052602481018290526044016105a2565b603554600090600160a01b900467ffffffffffffffff16610c65576000610c83565b603554610c8390600160a01b900467ffffffffffffffff1686611b9b565b9050838110610cc8576040517f2395edf200000000000000000000000000000000000000000000000000000000815260048101829052602481018590526044016105a2565b6000610cd48286611bbd565b6040805187815260208101859052919250606086901c9161ffff605088901c1691829133918e917f6410e64d304208a5e90fc76ab4fbf4e7b8836705daeda8dde27611ae0524490a910160405180910390a48315610dc757603554604080517f61d027b30000000000000000000000000000000000000000000000000000000081529051610dc7926001600160a01b0316916361d027b39160048083019260209291908290030181865afa158015610d90573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610db49190611bdb565b6034546001600160a01b03169086610ef5565b5090999098509650505050505050565b60006affffffffffffffffffffff821115610e28576040517f6dfcc65000000000000000000000000000000000000000000000000000000000815260586004820152602481018390526044016105a2565b5090565b6032805473ffffffffffffffffffffffffffffffffffffffff191690556105b481611350565b6040517fdd62ed3e0000000000000000000000000000000000000000000000000000000081523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015610ebb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610edf9190611b51565b905061070e8484610ef08585611bf8565b6113af565b6040516001600160a01b0383811660248301526044820183905261084991859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050611469565b6001546000906001600160a01b0316610f8860c0850160a08601611b0d565b6001600160a01b031614610fde5760405162461bcd60e51b815260206004820152601660248201527f5661756c742061646472657373206d69736d617463680000000000000000000060448201526064016105a2565b6000610ffe610fec866114e5565b610ff96020870187611c1d565b61154a565b60405163ffffffff4216815290915081907fa3ed7aef0745e1a91addae9e5daee7a8ace74852fec840b9d93da747855dd7b99060200160405180910390a26000546040517f86f014390000000000000000000000000000000000000000000000000000000081526001600160a01b03909116906386f014399061108990889088908890600401611ce5565b600060405180830381600087803b1580156110a357600080fd5b505af11580156110b7573d6000803e3d6000fd5b509293505050505b9392505050565b600080546040517fb02c43d0000000000000000000000000000000000000000000000000000000008152600481018490528291829182916001600160a01b03169063b02c43d09060240160e060405180830381865afa15801561112d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111519190611e60565b9050806040015163ffffffff166000036111ad5760405162461bcd60e51b815260206004820152601760248201527f4465706f736974206e6f7420696e697469616c697a656400000000000000000060448201526064016105a2565b6001546040517f6c626aa4000000000000000000000000000000000000000000000000000000008152600481018790526000916001600160a01b031690636c626aa49060240160408051808303816000875af1158015611211573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112359190611f1a565b9150508160a0015163ffffffff16600014158061125b575067ffffffffffffffff811615155b6112cd5760405162461bcd60e51b815260206004820152602360248201527f4465706f736974206e6f742066696e616c697a6564206279207468652062726960448201527f646765000000000000000000000000000000000000000000000000000000000060648201526084016105a2565b6402540be400826020015167ffffffffffffffff166112ec9190611f54565b945061130082602001518360800151611594565b6040805182815263ffffffff4216602082015291955087917f417b6288c9f637614f8b3f7a275fb4e44e517930fde949e463d58dfe0b97f28b910160405180910390a25060c00151929491935050565b603180546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f095ea7b30000000000000000000000000000000000000000000000000000000017905261142e8482611717565b61070e576040516001600160a01b0384811660248301526000604483015261146391869182169063095ea7b390606401610f22565b61070e84825b600061147e6001600160a01b038416836117bf565b905080516000141580156114a35750808060200190518101906114a19190611f6b565b155b15610849576040517f5274afe70000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024016105a2565b60006104756114f76020840184611f8d565b6115046020850185611fa8565b6115116040870187611fa8565b6115216080890160608a01611f8d565b60405160200161153696959493929190611fef565b6040516020818303038152906040526117cd565b6000828260405160200161157592919091825260e01b6001600160e01b031916602082015260240190565b60408051601f1981840301815291905280516020909101209392505050565b6000806402540be4006115a78486612031565b67ffffffffffffffff166115bb9190611f54565b90506000600160009054906101000a90046001600160a01b03166001600160a01b03166309b53f516040518163ffffffff1660e01b8152600401602060405180830381865afa158015611612573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116369190612059565b63ffffffff169050600080821161164e576000611658565b6116588284611b9b565b905060008060009054906101000a90046001600160a01b03166001600160a01b031663c42b64d06040518163ffffffff1660e01b8152600401608060405180830381865afa1580156116ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116d29190612076565b509250505060006402540be4008267ffffffffffffffff166116f49190611f54565b9050806117018487611bbd565b61170b9190611bbd565b98975050505050505050565b6000806000846001600160a01b03168460405161173491906120d5565b6000604051808303816000865af19150503d8060008114611771576040519150601f19603f3d011682016040523d82523d6000602084013e611776565b606091505b50915091508180156117a05750805115806117a05750808060200190518101906117a09190611f6b565b80156117b657506000856001600160a01b03163b115b95945050505050565b6060610472838360006117f4565b60006020600083516020850160025afa50602060006020600060025afa5050600051919050565b606081471015611832576040517fcd7860590000000000000000000000000000000000000000000000000000000081523060048201526024016105a2565b600080856001600160a01b0316848660405161184e91906120d5565b60006040518083038185875af1925050503d806000811461188b576040519150601f19603f3d011682016040523d82523d6000602084013e611890565b606091505b50915091506118a08683836118aa565b9695505050505050565b6060826118bf576118ba8261191f565b6110bf565b81511580156118d657506001600160a01b0384163b155b15611918576040517f9996b3150000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024016105a2565b50806110bf565b80511561192f5780518082602001fd5b6040517f1425ea4200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b67ffffffffffffffff811681146105b457600080fd5b60006020828403121561198957600080fd5b81356110bf81611961565b6001600160a01b03811681146105b457600080fd5b80356119b481611994565b919050565b803561ffff811681146119b457600080fd5b600080604083850312156119de57600080fd5b82356119e981611994565b91506119f7602084016119b9565b90509250929050565b600060208284031215611a1257600080fd5b5035919050565b634e487b7160e01b600052602160045260246000fd5b60068110611a4d57634e487b7160e01b600052602160045260246000fd5b9052565b60608101611a5f8286611a2f565b6001600160a01b03841660208301526affffffffffffffffffffff83166040830152949350505050565b600080600080848603610120811215611aa157600080fd5b853567ffffffffffffffff811115611ab857600080fd5b860160808189031215611aca57600080fd5b945060c0601f1982011215611ade57600080fd5b5060208501925060e0850135611af381611994565b9150611b0261010086016119b9565b905092959194509250565b600060208284031215611b1f57600080fd5b81356110bf81611994565b80516020808301519190811015611b4b576000198160200360031b1b821691505b50919050565b600060208284031215611b6357600080fd5b5051919050565b60408101611b788285611a2f565b6110bf6020830184611a2f565b634e487b7160e01b600052601160045260246000fd5b600082611bb857634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561047557610475611b85565b80516119b481611994565b600060208284031215611bed57600080fd5b81516110bf81611994565b8082018082111561047557610475611b85565b63ffffffff811681146105b457600080fd5b600060208284031215611c2f57600080fd5b81356110bf81611c0b565b80356001600160e01b0319811681146119b457600080fd5b6000808335601e19843603018112611c6957600080fd5b830160208101925035905067ffffffffffffffff811115611c8957600080fd5b803603821315611c9857600080fd5b9250929050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b80356bffffffffffffffffffffffff19811681146119b457600080fd5b60006101008083526001600160e01b031980611d0088611c3a565b1682850152611d126020880188611c52565b92506080610120860152611d2b61018086018483611c9f565b925050611d3b6040880188611c52565b85840360ff1901610140870152611d53848284611c9f565b9350505080611d6460608901611c3a565b166101608501525090508335611d7981611c0b565b63ffffffff811660208401525060208401357fffffffffffffffff0000000000000000000000000000000000000000000000008116808214611dba57600080fd5b80604085015250506bffffffffffffffffffffffff19611ddc60408601611cc8565b166060830152611dee60608501611cc8565b6bffffffffffffffffffffffff198116608084015250611e1060808501611c3a565b6001600160e01b0319811660a084015250611e2d60a085016119a9565b6001600160a01b031660c083015260e09091019190915292915050565b80516119b481611961565b80516119b481611c0b565b600060e08284031215611e7257600080fd5b60405160e0810181811067ffffffffffffffff82111715611ea357634e487b7160e01b600052604160045260246000fd5b604052611eaf83611bd0565b8152611ebd60208401611e4a565b6020820152611ece60408401611e55565b6040820152611edf60608401611bd0565b6060820152611ef060808401611e4a565b6080820152611f0160a08401611e55565b60a082015260c083015160c08201528091505092915050565b60008060408385031215611f2d57600080fd5b8251611f3881611961565b6020840151909250611f4981611961565b809150509250929050565b808202811582820484141761047557610475611b85565b600060208284031215611f7d57600080fd5b815180151581146110bf57600080fd5b600060208284031215611f9f57600080fd5b61047282611c3a565b6000808335601e19843603018112611fbf57600080fd5b83018035915067ffffffffffffffff821115611fda57600080fd5b602001915036819003821315611c9857600080fd5b60006001600160e01b03198089168352868860048501378683016004810160008152868882375093169390920160048101939093525050600801949350505050565b67ffffffffffffffff82811682821603908082111561205257612052611b85565b5092915050565b60006020828403121561206b57600080fd5b81516110bf81611c0b565b6000806000806080858703121561208c57600080fd5b845161209781611961565b60208601519094506120a881611961565b60408601519093506120b981611961565b60608601519092506120ca81611c0b565b939692955090935050565b6000825160005b818110156120f657602081860181015185830152016120dc565b50600092019182525091905056fea2646970667358221220462bf22e2a3e5c424c7897cc702ca2994745ded2b209ca480d6b59b6977ef88a64736f6c63430008150033", - "devdoc": { - "errors": { - "AddressEmptyCode(address)": [ - { - "details": "There's no code at `target` (it is not a contract)." - } - ], - "AddressInsufficientBalance(address)": [ - { - "details": "The ETH balance of the account is not enough to perform the operation." - } - ], - "BridgingCompletionAlreadyNotified()": [ - { - "details": "Attempted to notify a bridging completion, while it was already notified." - } - ], - "BridgingFinalizationAlreadyCalled()": [ - { - "details": "Attempted to call bridging finalization for a stake request for which the function was already called." - } - ], - "BridgingNotCompleted()": [ - { - "details": "Attempted to finalize a stake request, while bridging completion has not been notified yet." - } - ], - "CallerNotStaker()": [ - { - "details": "Attempted to call function by an account that is not the staker." - } - ], - "DepositorFeeExceedsBridgedAmount(uint256,uint256)": [ - { - "details": "Calculated depositor fee exceeds the amount of minted tBTC tokens." - } - ], - "FailedInnerCall()": [ - { - "details": "A call to an address target failed. The target may have reverted." - } - ], - "InsufficientTbtcBalance(uint256,uint256)": [ - { - "details": "Attempted to finalize bridging with depositor's contract tBTC balance lower than the calculated bridged tBTC amount. This error means that Governance should top-up the tBTC reserve for bridging fees approximation." - } - ], - "OwnableInvalidOwner(address)": [ - { - "details": "The owner is not a valid owner account. (eg. `address(0)`)" - } - ], - "OwnableUnauthorizedAccount(address)": [ - { - "details": "The caller account is not authorized to perform an operation." - } - ], - "SafeCastOverflowedUintDowncast(uint8,uint256)": [ - { - "details": "Value doesn't fit in an uint of `bits` size." - } - ], - "SafeERC20FailedOperation(address)": [ - { - "details": "An operation with an ERC20 token failed." - } - ], - "StakeRequestNotQueued()": [ - { - "details": "Attempted to finalize or cancel a stake request that was not added to the queue, or was already finalized or cancelled." - } - ], - "StakerIsZeroAddress()": [ - { - "details": "Staker address is zero." - } - ], - "UnexpectedStakeRequestState(uint8,uint8)": [ - { - "details": "Attempted to execute function for stake request in unexpected current state." - } - ] }, - "events": { - "BridgingCompleted(uint256,address,uint16,uint256,uint256)": { - "params": { - "bridgedAmount": "Amount of tBTC tokens that was bridged by the tBTC bridge.", - "caller": "Address that notified about bridging completion.", - "depositKey": "Deposit key identifying the deposit.", - "depositorFee": "Depositor fee amount.", - "referral": "Identifier of a partner in the referral program." - } - }, - "DepositorFeeDivisorUpdated(uint64)": { - "params": { - "depositorFeeDivisor": "New value of the depositor fee divisor." - } - }, - "StakeRequestCancelledFromQueue(uint256,address,uint256)": { - "params": { - "amountToStake": "Amount of queued tBTC tokens that got cancelled.", - "depositKey": "Deposit key identifying the deposit.", - "staker": "Address of the staker." - } - }, - "StakeRequestFinalized(uint256,address,uint256)": { - "details": "Deposit details can be fetched from {{ ERC4626.Deposit }} event emitted in the same transaction.", - "params": { - "caller": "Address that finalized the stake request.", - "depositKey": "Deposit key identifying the deposit.", - "stakedAmount": "Amount of staked tBTC tokens." - } - }, - "StakeRequestFinalizedFromQueue(uint256,address,uint256)": { - "details": "Deposit details can be fetched from {{ ERC4626.Deposit }} event emitted in the same transaction.", - "params": { - "caller": "Address that finalized the stake request.", - "depositKey": "Deposit key identifying the deposit.", - "stakedAmount": "Amount of staked tBTC tokens." - } - }, - "StakeRequestInitialized(uint256,address,address)": { - "details": "Deposit details can be fetched from {{ Bridge.DepositRevealed }} event emitted in the same transaction.", - "params": { - "caller": "Address that initialized the stake request.", - "depositKey": "Deposit key identifying the deposit.", - "staker": "The address to which the stBTC shares will be minted." - } - }, - "StakeRequestQueued(uint256,address,uint256)": { - "params": { - "caller": "Address that finalized the stake request.", - "depositKey": "Deposit key identifying the deposit.", - "queuedAmount": "Amount of queued tBTC tokens." - } - } - }, - "kind": "dev", - "methods": { - "acceptOwnership()": { - "details": "The new owner accepts the ownership transfer." - }, - "cancelQueuedStake(uint256)": { - "details": "This function can be called only after the stake request was added to queue.Only staker provided in the extra data of the stake request can call this function.", - "params": { - "depositKey": "Deposit key identifying the deposit." - } - }, - "constructor": { - "params": { - "_stbtc": "stBTC contract instance.", - "_tbtcToken": "tBTC token contract instance.", - "bridge": "tBTC Bridge contract instance.", - "tbtcVault": "tBTC Vault contract instance." - } - }, - "decodeExtraData(bytes32)": { - "details": "Unpacks the data from bytes32: 20 bytes of staker address and 2 bytes of referral, 10 bytes of trailing zeros.", - "params": { - "extraData": "Encoded extra data." - }, - "returns": { - "referral": "Data used for referral program.", - "staker": "The address to which the stBTC shares will be minted." - } - }, - "encodeExtraData(address,uint16)": { - "details": "Packs the data to bytes32: 20 bytes of staker address and 2 bytes of referral, 10 bytes of trailing zeros.", - "params": { - "referral": "Data used for referral program.", - "staker": "The address to which the stBTC shares will be minted." - }, - "returns": { - "_0": "Encoded extra data." - } - }, - "finalizeQueuedStake(uint256)": { - "params": { - "depositKey": "Deposit key identifying the deposit." - } - }, - "finalizeStake(uint256)": { - "details": "In case depositing in stBTC vault fails (e.g. because of the maximum deposit limit being reached), the `queueStake` function should be called to add the stake request to the staking queue.", - "params": { - "depositKey": "Deposit key identifying the deposit." - } - }, - "initializeStake((bytes4,bytes,bytes,bytes4),(uint32,bytes8,bytes20,bytes20,bytes4,address),address,uint16)": { - "details": "Requirements: - The revealed vault address must match the TBTCVault address, - All requirements from {Bridge#revealDepositWithExtraData} function must be met. - `staker` must be the staker address used in the P2(W)SH BTC deposit transaction as part of the extra data. - `referral` must be the referral info used in the P2(W)SH BTC deposit transaction as part of the extra data. - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex` can be revealed only one time.", - "params": { - "fundingTx": "Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.", - "referral": "Data used for referral program.", - "reveal": "Deposit reveal data, see `IBridgeTypes.DepositRevealInfo`.", - "staker": "The address to which the stBTC shares will be minted." - } - }, - "owner()": { - "details": "Returns the address of the current owner." - }, - "pendingOwner()": { - "details": "Returns the address of the pending owner." - }, - "queueStake(uint256)": { - "details": "It queues the stake request, until the stBTC vault is ready to accept the deposit. The request must be finalized with `finalizeQueuedStake` after the limit is increased or other user withdraws their funds from the stBTC contract to make place for another deposit. The staker has a possibility to submit `cancelQueuedStake` that will withdraw the minted tBTC token and abort staking process.", - "params": { - "depositKey": "Deposit key identifying the deposit." - } - }, - "renounceOwnership()": { - "details": "Leaves the contract without owner. It will not be possible to call `onlyOwner` functions. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby disabling any functionality that is only available to the owner." - }, - "transferOwnership(address)": { - "details": "Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. Can only be called by the current owner." - }, - "updateDepositorFeeDivisor(uint64)": { - "params": { - "newDepositorFeeDivisor": "New depositor fee divisor value." - } - } - }, - "stateVariables": { - "depositorFeeDivisor": { - "details": "That fee is computed as follows: `depositorFee = depositedAmount / depositorFeeDivisor` for example, if the depositor fee needs to be 2% of each deposit, the `depositorFeeDivisor` should be set to `50` because `1/50 = 0.02 = 2%`." - }, - "stakeRequests": { - "details": "The key is a deposit key identifying the deposit." - } - }, - "title": "Acre Bitcoin Depositor contract.", - "version": 1 - }, - "userdoc": { - "errors": { - "StbtcZeroAddress()": [ + { + "inputs": [ { - "notice": "Reverts if the stBTC address is zero." + "internalType": "uint256", + "name": "newMinDepositAmount", + "type": "uint256" } ], - "TbtcTokenZeroAddress()": [ - { - "notice": "Reverts if the tBTC Token address is zero." - } - ] - }, - "events": { - "BridgingCompleted(uint256,address,uint16,uint256,uint256)": { - "notice": "Emitted when bridging completion has been notified." - }, - "DepositorFeeDivisorUpdated(uint64)": { - "notice": "Emitted when a depositor fee divisor is updated." - }, - "StakeRequestCancelledFromQueue(uint256,address,uint256)": { - "notice": "Emitted when a queued stake request is cancelled." - }, - "StakeRequestFinalized(uint256,address,uint256)": { - "notice": "Emitted when a stake request is finalized." - }, - "StakeRequestFinalizedFromQueue(uint256,address,uint256)": { - "notice": "Emitted when a stake request is finalized from the queue." - }, - "StakeRequestInitialized(uint256,address,address)": { - "notice": "Emitted when a stake request is initialized." - }, - "StakeRequestQueued(uint256,address,uint256)": { - "notice": "Emitted when a stake request is queued." - } - }, - "kind": "user", - "methods": { - "SATOSHI_MULTIPLIER()": { - "notice": "Multiplier to convert satoshi to TBTC token units." - }, - "bridge()": { - "notice": "Bridge contract address." - }, - "cancelQueuedStake(uint256)": { - "notice": "Cancel queued stake. The function can be called by the staker to recover tBTC that cannot be finalized to stake in stBTC contract due to a deposit limit being reached." - }, - "constructor": { - "notice": "Acre Bitcoin Depositor contract constructor." - }, - "decodeExtraData(bytes32)": { - "notice": "Decodes staker address and referral from extra data." - }, - "depositorFeeDivisor()": { - "notice": "Divisor used to compute the depositor fee taken from each deposit and transferred to the treasury upon stake request finalization." - }, - "encodeExtraData(address,uint16)": { - "notice": "Encodes staker address and referral as extra data." - }, - "finalizeQueuedStake(uint256)": { - "notice": "This function should be called for previously queued stake request, when stBTC vault is able to accept a deposit." - }, - "finalizeStake(uint256)": { - "notice": "This function should be called for previously initialized stake request, after tBTC bridging process was finalized. It stakes the tBTC from the given deposit into stBTC, emitting the stBTC shares to the staker specified in the deposit extra data and using the referral provided in the extra data." - }, - "initializeStake((bytes4,bytes,bytes,bytes4),(uint32,bytes8,bytes20,bytes20,bytes4,address),address,uint16)": { - "notice": "This function allows staking process initialization for a Bitcoin deposit made by an user with a P2(W)SH transaction. It uses the supplied information to reveal a deposit to the tBTC Bridge contract." - }, - "queueStake(uint256)": { - "notice": "This function should be called for previously initialized stake request, after tBTC bridging process was finalized, in case the `finalizeStake` failed due to stBTC vault deposit limit being reached." - }, - "stakeRequests(uint256)": { - "notice": "Mapping of stake requests." - }, - "stbtc()": { - "notice": "stBTC contract." - }, - "tbtcToken()": { - "notice": "tBTC Token contract." - }, - "tbtcVault()": { - "notice": "TBTCVault contract address." - }, - "updateDepositorFeeDivisor(uint64)": { - "notice": "Updates the depositor fee divisor." - } - }, - "notice": "The contract integrates Acre staking with tBTC minting. User who wants to stake BTC in Acre should submit a Bitcoin transaction to the most recently created off-chain ECDSA wallets of the tBTC Bridge using pay-to-script-hash (P2SH) or pay-to-witness-script-hash (P2WSH) containing hashed information about this Depositor contract address, and staker's Ethereum address. Then, the staker initiates tBTC minting by revealing their Ethereum address along with their deposit blinding factor, refund public key hash and refund locktime on the tBTC Bridge through this Depositor contract. The off-chain ECDSA wallet and Optimistic Minting bots listen for these sorts of messages and when they get one, they check the Bitcoin network to make sure the deposit lines up. Majority of tBTC minting is finalized by the Optimistic Minting process, where Minter bot initializes minting process and if there is no veto from the Guardians, the process is finalized and tBTC minted to the Depositor address. If the revealed deposit is not handled by the Optimistic Minting process the off-chain ECDSA wallet may decide to pick the deposit transaction for sweeping, and when the sweep operation is confirmed on the Bitcoin network, the tBTC Bridge and tBTC vault mint the tBTC token to the Depositor address. After tBTC is minted to the Depositor, on the stake finalization tBTC is staked in stBTC contract and stBTC shares are emitted to the staker.", - "version": 1 - }, - "storageLayout": { - "storage": [ - { - "astId": 2683, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "bridge", - "offset": 0, - "slot": "0", - "type": "t_contract(IBridge)3087" - }, - { - "astId": 2687, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "tbtcVault", - "offset": 0, - "slot": "1", - "type": "t_contract(ITBTCVault)3107" - }, - { - "astId": 2691, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "__gap", - "offset": 0, - "slot": "2", - "type": "t_array(t_uint256)47_storage" - }, - { - "astId": 3585, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "_owner", - "offset": 0, - "slot": "49", - "type": "t_address" - }, - { - "astId": 3733, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "_pendingOwner", - "offset": 0, - "slot": "50", - "type": "t_address" - }, - { - "astId": 8874, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "stakeRequests", - "offset": 0, - "slot": "51", - "type": "t_mapping(t_uint256,t_struct(StakeRequest)8868_storage)" - }, - { - "astId": 8878, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "tbtcToken", - "offset": 0, - "slot": "52", - "type": "t_contract(IERC20)4710" - }, - { - "astId": 8882, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "stbtc", - "offset": 0, - "slot": "53", - "type": "t_contract(stBTC)10351" - }, - { - "astId": 8885, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "depositorFeeDivisor", - "offset": 20, - "slot": "53", - "type": "t_uint64" - } - ], - "types": { - "t_address": { - "encoding": "inplace", - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_uint256)47_storage": { - "base": "t_uint256", - "encoding": "inplace", - "label": "uint256[47]", - "numberOfBytes": "1504" - }, - "t_contract(IBridge)3087": { - "encoding": "inplace", - "label": "contract IBridge", - "numberOfBytes": "20" - }, - "t_contract(IERC20)4710": { - "encoding": "inplace", - "label": "contract IERC20", - "numberOfBytes": "20" - }, - "t_contract(ITBTCVault)3107": { - "encoding": "inplace", - "label": "contract ITBTCVault", - "numberOfBytes": "20" - }, - "t_contract(stBTC)10351": { - "encoding": "inplace", - "label": "contract stBTC", - "numberOfBytes": "20" - }, - "t_enum(StakeRequestState)8860": { - "encoding": "inplace", - "label": "enum AcreBitcoinDepositor.StakeRequestState", - "numberOfBytes": "1" - }, - "t_mapping(t_uint256,t_struct(StakeRequest)8868_storage)": { - "encoding": "mapping", - "key": "t_uint256", - "label": "mapping(uint256 => struct AcreBitcoinDepositor.StakeRequest)", - "numberOfBytes": "32", - "value": "t_struct(StakeRequest)8868_storage" - }, - "t_struct(StakeRequest)8868_storage": { - "encoding": "inplace", - "label": "struct AcreBitcoinDepositor.StakeRequest", - "members": [ - { - "astId": 8863, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "state", - "offset": 0, - "slot": "0", - "type": "t_enum(StakeRequestState)8860" - }, - { - "astId": 8865, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "staker", - "offset": 1, - "slot": "0", - "type": "t_address" - }, - { - "astId": 8867, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "queuedAmount", - "offset": 21, - "slot": "0", - "type": "t_uint88" - } - ], - "numberOfBytes": "32" - }, - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint64": { - "encoding": "inplace", - "label": "uint64", - "numberOfBytes": "8" - }, - "t_uint88": { - "encoding": "inplace", - "label": "uint88", - "numberOfBytes": "11" - } + "name": "updateMinDepositAmount", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" } - } + ], + "transactionHash": "0xf48fcfd4e3bed67f73675366c46427b9a19c29a25ea3a4432bbb48df240a6785", + "numDeployments": 1, + "implementation": "0x859aB3c72642d07c3c389817624a9D8da06BBF71", + "devdoc": "Contract deployed as upgradable proxy" } \ No newline at end of file diff --git a/solidity/deployments/sepolia/BitcoinRedeemer.json b/solidity/deployments/sepolia/BitcoinRedeemer.json new file mode 100644 index 000000000..d5e796479 --- /dev/null +++ b/solidity/deployments/sepolia/BitcoinRedeemer.json @@ -0,0 +1,354 @@ +{ + "address": "0x0E781e9D538895EE99bd6e9Bf28664942beFF32f", + "abi": [ + { + "inputs": [], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "inputs": [], + "name": "ApproveAndCallFailed", + "type": "error" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "caller", + "type": "address" + } + ], + "name": "CallerNotAllowed", + "type": "error" + }, + { + "inputs": [], + "name": "EmptyExtraData", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidInitialization", + "type": "error" + }, + { + "inputs": [], + "name": "NotInitializing", + "type": "error" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "OwnableInvalidOwner", + "type": "error" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "OwnableUnauthorizedAccount", + "type": "error" + }, + { + "inputs": [], + "name": "StbtcZeroAddress", + "type": "error" + }, + { + "inputs": [], + "name": "TbtcTokenZeroAddress", + "type": "error" + }, + { + "inputs": [], + "name": "TbtcVaultZeroAddress", + "type": "error" + }, + { + "inputs": [], + "name": "UnexpectedTbtcTokenOwner", + "type": "error" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "token", + "type": "address" + } + ], + "name": "UnsupportedToken", + "type": "error" + }, + { + "inputs": [], + "name": "ZeroAddress", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint64", + "name": "version", + "type": "uint64" + } + ], + "name": "Initialized", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferStarted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "tbtcAmount", + "type": "uint256" + } + ], + "name": "RedemptionRequested", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldTbtcVault", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newTbtcVault", + "type": "address" + } + ], + "name": "TbtcVaultUpdated", + "type": "event" + }, + { + "inputs": [], + "name": "acceptOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_tbtcToken", + "type": "address" + }, + { + "internalType": "address", + "name": "_stbtc", + "type": "address" + }, + { + "internalType": "address", + "name": "_tbtcVault", + "type": "address" + } + ], + "name": "initialize", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "pendingOwner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "from", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + }, + { + "internalType": "address", + "name": "token", + "type": "address" + }, + { + "internalType": "bytes", + "name": "extraData", + "type": "bytes" + } + ], + "name": "receiveApproval", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "stbtc", + "outputs": [ + { + "internalType": "contract stBTC", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "tbtcToken", + "outputs": [ + { + "internalType": "contract ITBTCToken", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "tbtcVault", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newTbtcVault", + "type": "address" + } + ], + "name": "updateTbtcVault", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0xa7da2f83d258beac8b9f05d14ff2452842c535d8624f91ae31b4a4857ad1eecf", + "numDeployments": 1, + "implementation": "0x88B0Aa9BAfB9573871683b49407cD7d99668C786", + "devdoc": "Contract deployed as upgradable proxy" +} \ No newline at end of file diff --git a/solidity/deployments/sepolia/MezoAllocator.json b/solidity/deployments/sepolia/MezoAllocator.json new file mode 100644 index 000000000..bd0f325ed --- /dev/null +++ b/solidity/deployments/sepolia/MezoAllocator.json @@ -0,0 +1,513 @@ +{ + "address": "0x43D17826b31E03c11b46427B68613422A3621b6f", + "abi": [ + { + "inputs": [], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "target", + "type": "address" + } + ], + "name": "AddressEmptyCode", + "type": "error" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "AddressInsufficientBalance", + "type": "error" + }, + { + "inputs": [], + "name": "CallerNotMaintainer", + "type": "error" + }, + { + "inputs": [], + "name": "CallerNotStbtc", + "type": "error" + }, + { + "inputs": [], + "name": "FailedInnerCall", + "type": "error" + }, + { + "inputs": [], + "name": "InvalidInitialization", + "type": "error" + }, + { + "inputs": [], + "name": "MaintainerAlreadyRegistered", + "type": "error" + }, + { + "inputs": [], + "name": "MaintainerNotRegistered", + "type": "error" + }, + { + "inputs": [], + "name": "NotInitializing", + "type": "error" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "OwnableInvalidOwner", + "type": "error" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "OwnableUnauthorizedAccount", + "type": "error" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "token", + "type": "address" + } + ], + "name": "SafeERC20FailedOperation", + "type": "error" + }, + { + "inputs": [], + "name": "ZeroAddress", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "uint256", + "name": "oldDepositId", + "type": "uint256" + }, + { + "indexed": true, + "internalType": "uint256", + "name": "newDepositId", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "addedAmount", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "newDepositAmount", + "type": "uint256" + } + ], + "name": "DepositAllocated", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "uint256", + "name": "depositId", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "DepositReleased", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "uint256", + "name": "depositId", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "DepositWithdrawn", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint64", + "name": "version", + "type": "uint64" + } + ], + "name": "Initialized", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "maintainer", + "type": "address" + } + ], + "name": "MaintainerAdded", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "maintainer", + "type": "address" + } + ], + "name": "MaintainerRemoved", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferStarted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "inputs": [], + "name": "acceptOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "maintainerToAdd", + "type": "address" + } + ], + "name": "addMaintainer", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "allocate", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "depositBalance", + "outputs": [ + { + "internalType": "uint96", + "name": "", + "type": "uint96" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "depositId", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "getMaintainers", + "outputs": [ + { + "internalType": "address[]", + "name": "", + "type": "address[]" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_mezoPortal", + "type": "address" + }, + { + "internalType": "address", + "name": "_tbtc", + "type": "address" + }, + { + "internalType": "address", + "name": "_stbtc", + "type": "address" + } + ], + "name": "initialize", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "isMaintainer", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "name": "maintainers", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "mezoPortal", + "outputs": [ + { + "internalType": "contract IMezoPortal", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "pendingOwner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "releaseDeposit", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "maintainerToRemove", + "type": "address" + } + ], + "name": "removeMaintainer", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "stbtc", + "outputs": [ + { + "internalType": "contract stBTC", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "tbtc", + "outputs": [ + { + "internalType": "contract IERC20", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalAssets", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "withdraw", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0xfb55581567b9c25430937117bb3e1f52bae0f4431d90c0984d1998cac74b1f73", + "numDeployments": 1, + "implementation": "0x09F851AD4e927755453E253557A5383B67925a35", + "devdoc": "Contract deployed as upgradable proxy" +} \ No newline at end of file diff --git a/solidity/deployments/sepolia/solcInputs/49f0432287e96a47d66ba17ae7bf5d96.json b/solidity/deployments/sepolia/solcInputs/49f0432287e96a47d66ba17ae7bf5d96.json deleted file mode 100644 index dcd762398..000000000 --- a/solidity/deployments/sepolia/solcInputs/49f0432287e96a47d66ba17ae7bf5d96.json +++ /dev/null @@ -1,117 +0,0 @@ -{ - "language": "Solidity", - "sources": { - "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol": { - "content": "pragma solidity ^0.8.4;\n\n/** @title BitcoinSPV */\n/** @author Summa (https://summa.one) */\n\nimport {BytesLib} from \"./BytesLib.sol\";\nimport {SafeMath} from \"./SafeMath.sol\";\n\nlibrary BTCUtils {\n using BytesLib for bytes;\n using SafeMath for uint256;\n\n // The target at minimum Difficulty. Also the target of the genesis block\n uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000;\n\n uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds\n uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks\n\n uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n /* ***** */\n /* UTILS */\n /* ***** */\n\n /// @notice Determines the length of a VarInt in bytes\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\n /// @param _flag The first byte of a VarInt\n /// @return The number of non-flag bytes in the VarInt\n function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) {\n return determineVarIntDataLengthAt(_flag, 0);\n }\n\n /// @notice Determines the length of a VarInt in bytes\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\n /// @param _b The byte array containing a VarInt\n /// @param _at The position of the VarInt in the array\n /// @return The number of non-flag bytes in the VarInt\n function determineVarIntDataLengthAt(bytes memory _b, uint256 _at) internal pure returns (uint8) {\n if (uint8(_b[_at]) == 0xff) {\n return 8; // one-byte flag, 8 bytes data\n }\n if (uint8(_b[_at]) == 0xfe) {\n return 4; // one-byte flag, 4 bytes data\n }\n if (uint8(_b[_at]) == 0xfd) {\n return 2; // one-byte flag, 2 bytes data\n }\n\n return 0; // flag is data\n }\n\n /// @notice Parse a VarInt into its data length and the number it represents\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\n /// Caller SHOULD explicitly handle this case (or bubble it up)\n /// @param _b A byte-string starting with a VarInt\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\n function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) {\n return parseVarIntAt(_b, 0);\n }\n\n /// @notice Parse a VarInt into its data length and the number it represents\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\n /// Caller SHOULD explicitly handle this case (or bubble it up)\n /// @param _b A byte-string containing a VarInt\n /// @param _at The position of the VarInt\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\n function parseVarIntAt(bytes memory _b, uint256 _at) internal pure returns (uint256, uint256) {\n uint8 _dataLen = determineVarIntDataLengthAt(_b, _at);\n\n if (_dataLen == 0) {\n return (0, uint8(_b[_at]));\n }\n if (_b.length < 1 + _dataLen + _at) {\n return (ERR_BAD_ARG, 0);\n }\n uint256 _number;\n if (_dataLen == 2) {\n _number = reverseUint16(uint16(_b.slice2(1 + _at)));\n } else if (_dataLen == 4) {\n _number = reverseUint32(uint32(_b.slice4(1 + _at)));\n } else if (_dataLen == 8) {\n _number = reverseUint64(uint64(_b.slice8(1 + _at)));\n }\n return (_dataLen, _number);\n }\n\n /// @notice Changes the endianness of a byte array\n /// @dev Returns a new, backwards, bytes\n /// @param _b The bytes to reverse\n /// @return The reversed bytes\n function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) {\n bytes memory _newValue = new bytes(_b.length);\n\n for (uint i = 0; i < _b.length; i++) {\n _newValue[_b.length - i - 1] = _b[i];\n }\n\n return _newValue;\n }\n\n /// @notice Changes the endianness of a uint256\n /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint256(uint256 _b) internal pure returns (uint256 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |\n ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);\n // swap 2-byte long pairs\n v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |\n ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);\n // swap 4-byte long pairs\n v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |\n ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);\n // swap 8-byte long pairs\n v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |\n ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);\n // swap 16-byte long pairs\n v = (v >> 128) | (v << 128);\n }\n\n /// @notice Changes the endianness of a uint64\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint64(uint64 _b) internal pure returns (uint64 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF00FF00FF) |\n ((v & 0x00FF00FF00FF00FF) << 8);\n // swap 2-byte long pairs\n v = ((v >> 16) & 0x0000FFFF0000FFFF) |\n ((v & 0x0000FFFF0000FFFF) << 16);\n // swap 4-byte long pairs\n v = (v >> 32) | (v << 32);\n }\n\n /// @notice Changes the endianness of a uint32\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint32(uint32 _b) internal pure returns (uint32 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF) |\n ((v & 0x00FF00FF) << 8);\n // swap 2-byte long pairs\n v = (v >> 16) | (v << 16);\n }\n\n /// @notice Changes the endianness of a uint24\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint24(uint24 _b) internal pure returns (uint24 v) {\n v = (_b << 16) | (_b & 0x00FF00) | (_b >> 16);\n }\n\n /// @notice Changes the endianness of a uint16\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint16(uint16 _b) internal pure returns (uint16 v) {\n v = (_b << 8) | (_b >> 8);\n }\n\n\n /// @notice Converts big-endian bytes to a uint\n /// @dev Traverses the byte array and sums the bytes\n /// @param _b The big-endian bytes-encoded integer\n /// @return The integer representation\n function bytesToUint(bytes memory _b) internal pure returns (uint256) {\n uint256 _number;\n\n for (uint i = 0; i < _b.length; i++) {\n _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));\n }\n\n return _number;\n }\n\n /// @notice Get the last _num bytes from a byte array\n /// @param _b The byte array to slice\n /// @param _num The number of bytes to extract from the end\n /// @return The last _num bytes of _b\n function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) {\n uint256 _start = _b.length.sub(_num);\n\n return _b.slice(_start, _num);\n }\n\n /// @notice Implements bitcoin's hash160 (rmd160(sha2()))\n /// @dev abi.encodePacked changes the return to bytes instead of bytes32\n /// @param _b The pre-image\n /// @return The digest\n function hash160(bytes memory _b) internal pure returns (bytes memory) {\n return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));\n }\n\n /// @notice Implements bitcoin's hash160 (sha2 + ripemd160)\n /// @dev sha2 precompile at address(2), ripemd160 at address(3)\n /// @param _b The pre-image\n /// @return res The digest\n function hash160View(bytes memory _b) internal view returns (bytes20 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\n pop(staticcall(gas(), 3, 0x00, 32, 0x00, 32))\n // read from position 12 = 0c\n res := mload(0x0c)\n }\n }\n\n /// @notice Implements bitcoin's hash256 (double sha2)\n /// @dev abi.encodePacked changes the return to bytes instead of bytes32\n /// @param _b The pre-image\n /// @return The digest\n function hash256(bytes memory _b) internal pure returns (bytes32) {\n return sha256(abi.encodePacked(sha256(_b)));\n }\n\n /// @notice Implements bitcoin's hash256 (double sha2)\n /// @dev sha2 is precompiled smart contract located at address(2)\n /// @param _b The pre-image\n /// @return res The digest\n function hash256View(bytes memory _b) internal view returns (bytes32 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\n res := mload(0x00)\n }\n }\n\n /// @notice Implements bitcoin's hash256 on a pair of bytes32\n /// @dev sha2 is precompiled smart contract located at address(2)\n /// @param _a The first bytes32 of the pre-image\n /// @param _b The second bytes32 of the pre-image\n /// @return res The digest\n function hash256Pair(bytes32 _a, bytes32 _b) internal view returns (bytes32 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n mstore(0x00, _a)\n mstore(0x20, _b)\n pop(staticcall(gas(), 2, 0x00, 64, 0x00, 32))\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\n res := mload(0x00)\n }\n }\n\n /// @notice Implements bitcoin's hash256 (double sha2)\n /// @dev sha2 is precompiled smart contract located at address(2)\n /// @param _b The array containing the pre-image\n /// @param at The start of the pre-image\n /// @param len The length of the pre-image\n /// @return res The digest\n function hash256Slice(\n bytes memory _b,\n uint256 at,\n uint256 len\n ) internal view returns (bytes32 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n pop(staticcall(gas(), 2, add(_b, add(32, at)), len, 0x00, 32))\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\n res := mload(0x00)\n }\n }\n\n /* ************ */\n /* Legacy Input */\n /* ************ */\n\n /// @notice Extracts the nth input from the vin (0-indexed)\n /// @dev Iterates over the vin. If you need to extract several, write a custom function\n /// @param _vin The vin as a tightly-packed byte array\n /// @param _index The 0-indexed location of the input to extract\n /// @return The input as a byte array\n function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _nIns;\n\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\n require(_varIntDataLen != ERR_BAD_ARG, \"Read overrun during VarInt parsing\");\n require(_index < _nIns, \"Vin read overrun\");\n\n uint256 _len = 0;\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 _i = 0; _i < _index; _i ++) {\n _len = determineInputLengthAt(_vin, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n _offset = _offset + _len;\n }\n\n _len = determineInputLengthAt(_vin, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _vin.slice(_offset, _len);\n }\n\n /// @notice Determines whether an input is legacy\n /// @dev False if no scriptSig, otherwise True\n /// @param _input The input\n /// @return True for legacy, False for witness\n function isLegacyInput(bytes memory _input) internal pure returns (bool) {\n return _input[36] != hex\"00\";\n }\n\n /// @notice Determines the length of a scriptSig in an input\n /// @dev Will return 0 if passed a witness input.\n /// @param _input The LEGACY input\n /// @return The length of the script sig\n function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) {\n return extractScriptSigLenAt(_input, 0);\n }\n\n /// @notice Determines the length of a scriptSig in an input\n /// starting at the specified position\n /// @dev Will return 0 if passed a witness input.\n /// @param _input The byte array containing the LEGACY input\n /// @param _at The position of the input in the array\n /// @return The length of the script sig\n function extractScriptSigLenAt(bytes memory _input, uint256 _at) internal pure returns (uint256, uint256) {\n if (_input.length < 37 + _at) {\n return (ERR_BAD_ARG, 0);\n }\n\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = parseVarIntAt(_input, _at + 36);\n\n return (_varIntDataLen, _scriptSigLen);\n }\n\n /// @notice Determines the length of an input from its scriptSig\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\n /// @param _input The input\n /// @return The length of the input in bytes\n function determineInputLength(bytes memory _input) internal pure returns (uint256) {\n return determineInputLengthAt(_input, 0);\n }\n\n /// @notice Determines the length of an input from its scriptSig,\n /// starting at the specified position\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\n /// @param _input The byte array containing the input\n /// @param _at The position of the input in the array\n /// @return The length of the input in bytes\n function determineInputLengthAt(bytes memory _input, uint256 _at) internal pure returns (uint256) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLenAt(_input, _at);\n if (_varIntDataLen == ERR_BAD_ARG) {\n return ERR_BAD_ARG;\n }\n\n return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;\n }\n\n /// @notice Extracts the LE sequence bytes from an input\n /// @dev Sequence is used for relative time locks\n /// @param _input The LEGACY input\n /// @return The sequence bytes (LE uint)\n function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes4) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\n require(_varIntDataLen != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _input.slice4(36 + 1 + _varIntDataLen + _scriptSigLen);\n }\n\n /// @notice Extracts the sequence from the input\n /// @dev Sequence is a 4-byte little-endian number\n /// @param _input The LEGACY input\n /// @return The sequence number (big-endian uint)\n function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) {\n uint32 _leSeqence = uint32(extractSequenceLELegacy(_input));\n uint32 _beSequence = reverseUint32(_leSeqence);\n return _beSequence;\n }\n /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx\n /// @dev Will return hex\"00\" if passed a witness input\n /// @param _input The LEGACY input\n /// @return The length-prepended scriptSig\n function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\n require(_varIntDataLen != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);\n }\n\n\n /* ************* */\n /* Witness Input */\n /* ************* */\n\n /// @notice Extracts the LE sequence bytes from an input\n /// @dev Sequence is used for relative time locks\n /// @param _input The WITNESS input\n /// @return The sequence bytes (LE uint)\n function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes4) {\n return _input.slice4(37);\n }\n\n /// @notice Extracts the sequence from the input in a tx\n /// @dev Sequence is a 4-byte little-endian number\n /// @param _input The WITNESS input\n /// @return The sequence number (big-endian uint)\n function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) {\n uint32 _leSeqence = uint32(extractSequenceLEWitness(_input));\n uint32 _inputeSequence = reverseUint32(_leSeqence);\n return _inputeSequence;\n }\n\n /// @notice Extracts the outpoint from the input in a tx\n /// @dev 32-byte tx id with 4-byte index\n /// @param _input The input\n /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)\n function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) {\n return _input.slice(0, 36);\n }\n\n /// @notice Extracts the outpoint tx id from an input\n /// @dev 32-byte tx id\n /// @param _input The input\n /// @return The tx id (little-endian bytes)\n function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) {\n return _input.slice32(0);\n }\n\n /// @notice Extracts the outpoint tx id from an input\n /// starting at the specified position\n /// @dev 32-byte tx id\n /// @param _input The byte array containing the input\n /// @param _at The position of the input\n /// @return The tx id (little-endian bytes)\n function extractInputTxIdLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes32) {\n return _input.slice32(_at);\n }\n\n /// @notice Extracts the LE tx input index from the input in a tx\n /// @dev 4-byte tx index\n /// @param _input The input\n /// @return The tx index (little-endian bytes)\n function extractTxIndexLE(bytes memory _input) internal pure returns (bytes4) {\n return _input.slice4(32);\n }\n\n /// @notice Extracts the LE tx input index from the input in a tx\n /// starting at the specified position\n /// @dev 4-byte tx index\n /// @param _input The byte array containing the input\n /// @param _at The position of the input\n /// @return The tx index (little-endian bytes)\n function extractTxIndexLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes4) {\n return _input.slice4(32 + _at);\n }\n\n /* ****** */\n /* Output */\n /* ****** */\n\n /// @notice Determines the length of an output\n /// @dev Works with any properly formatted output\n /// @param _output The output\n /// @return The length indicated by the prefix, error if invalid length\n function determineOutputLength(bytes memory _output) internal pure returns (uint256) {\n return determineOutputLengthAt(_output, 0);\n }\n\n /// @notice Determines the length of an output\n /// starting at the specified position\n /// @dev Works with any properly formatted output\n /// @param _output The byte array containing the output\n /// @param _at The position of the output\n /// @return The length indicated by the prefix, error if invalid length\n function determineOutputLengthAt(bytes memory _output, uint256 _at) internal pure returns (uint256) {\n if (_output.length < 9 + _at) {\n return ERR_BAD_ARG;\n }\n uint256 _varIntDataLen;\n uint256 _scriptPubkeyLength;\n (_varIntDataLen, _scriptPubkeyLength) = parseVarIntAt(_output, 8 + _at);\n\n if (_varIntDataLen == ERR_BAD_ARG) {\n return ERR_BAD_ARG;\n }\n\n // 8-byte value, 1-byte for tag itself\n return 8 + 1 + _varIntDataLen + _scriptPubkeyLength;\n }\n\n /// @notice Extracts the output at a given index in the TxOuts vector\n /// @dev Iterates over the vout. If you need to extract multiple, write a custom function\n /// @param _vout The _vout to extract from\n /// @param _index The 0-indexed location of the output to extract\n /// @return The specified output\n function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _nOuts;\n\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\n require(_varIntDataLen != ERR_BAD_ARG, \"Read overrun during VarInt parsing\");\n require(_index < _nOuts, \"Vout read overrun\");\n\n uint256 _len = 0;\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 _i = 0; _i < _index; _i ++) {\n _len = determineOutputLengthAt(_vout, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptPubkey\");\n _offset += _len;\n }\n\n _len = determineOutputLengthAt(_vout, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptPubkey\");\n return _vout.slice(_offset, _len);\n }\n\n /// @notice Extracts the value bytes from the output in a tx\n /// @dev Value is an 8-byte little-endian number\n /// @param _output The output\n /// @return The output value as LE bytes\n function extractValueLE(bytes memory _output) internal pure returns (bytes8) {\n return _output.slice8(0);\n }\n\n /// @notice Extracts the value from the output in a tx\n /// @dev Value is an 8-byte little-endian number\n /// @param _output The output\n /// @return The output value\n function extractValue(bytes memory _output) internal pure returns (uint64) {\n uint64 _leValue = uint64(extractValueLE(_output));\n uint64 _beValue = reverseUint64(_leValue);\n return _beValue;\n }\n\n /// @notice Extracts the value from the output in a tx\n /// @dev Value is an 8-byte little-endian number\n /// @param _output The byte array containing the output\n /// @param _at The starting index of the output in the array\n /// @return The output value\n function extractValueAt(bytes memory _output, uint256 _at) internal pure returns (uint64) {\n uint64 _leValue = uint64(_output.slice8(_at));\n uint64 _beValue = reverseUint64(_leValue);\n return _beValue;\n }\n\n /// @notice Extracts the data from an op return output\n /// @dev Returns hex\"\" if no data or not an op return\n /// @param _output The output\n /// @return Any data contained in the opreturn output, null if not an op return\n function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) {\n if (_output[9] != hex\"6a\") {\n return hex\"\";\n }\n bytes1 _dataLen = _output[10];\n return _output.slice(11, uint256(uint8(_dataLen)));\n }\n\n /// @notice Extracts the hash from the output script\n /// @dev Determines type by the length prefix and validates format\n /// @param _output The output\n /// @return The hash committed to by the pk_script, or null for errors\n function extractHash(bytes memory _output) internal pure returns (bytes memory) {\n return extractHashAt(_output, 8, _output.length - 8);\n }\n\n /// @notice Extracts the hash from the output script\n /// @dev Determines type by the length prefix and validates format\n /// @param _output The byte array containing the output\n /// @param _at The starting index of the output script in the array\n /// (output start + 8)\n /// @param _len The length of the output script\n /// (output length - 8)\n /// @return The hash committed to by the pk_script, or null for errors\n function extractHashAt(\n bytes memory _output,\n uint256 _at,\n uint256 _len\n ) internal pure returns (bytes memory) {\n uint8 _scriptLen = uint8(_output[_at]);\n\n // don't have to worry about overflow here.\n // if _scriptLen + 1 overflows, then output length would have to be < 1\n // for this check to pass. if it's < 1, then we errored when assigning\n // _scriptLen\n if (_scriptLen + 1 != _len) {\n return hex\"\";\n }\n\n if (uint8(_output[_at + 1]) == 0) {\n if (_scriptLen < 2) {\n return hex\"\";\n }\n uint256 _payloadLen = uint8(_output[_at + 2]);\n // Check for maliciously formatted witness outputs.\n // No need to worry about underflow as long b/c of the `< 2` check\n if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) {\n return hex\"\";\n }\n return _output.slice(_at + 3, _payloadLen);\n } else {\n bytes3 _tag = _output.slice3(_at);\n // p2pkh\n if (_tag == hex\"1976a9\") {\n // Check for maliciously formatted p2pkh\n // No need to worry about underflow, b/c of _scriptLen check\n if (uint8(_output[_at + 3]) != 0x14 ||\n _output.slice2(_at + _len - 2) != hex\"88ac\") {\n return hex\"\";\n }\n return _output.slice(_at + 4, 20);\n //p2sh\n } else if (_tag == hex\"17a914\") {\n // Check for maliciously formatted p2sh\n // No need to worry about underflow, b/c of _scriptLen check\n if (uint8(_output[_at + _len - 1]) != 0x87) {\n return hex\"\";\n }\n return _output.slice(_at + 3, 20);\n }\n }\n return hex\"\"; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */\n }\n\n /* ********** */\n /* Witness TX */\n /* ********** */\n\n\n /// @notice Checks that the vin passed up is properly formatted\n /// @dev Consider a vin with a valid vout in its scriptsig\n /// @param _vin Raw bytes length-prefixed input vector\n /// @return True if it represents a validly formatted vin\n function validateVin(bytes memory _vin) internal pure returns (bool) {\n uint256 _varIntDataLen;\n uint256 _nIns;\n\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\n\n // Not valid if it says there are too many or no inputs\n if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) {\n return false;\n }\n\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 i = 0; i < _nIns; i++) {\n // If we're at the end, but still expect more\n if (_offset >= _vin.length) {\n return false;\n }\n\n // Grab the next input and determine its length.\n uint256 _nextLen = determineInputLengthAt(_vin, _offset);\n if (_nextLen == ERR_BAD_ARG) {\n return false;\n }\n\n // Increase the offset by that much\n _offset += _nextLen;\n }\n\n // Returns false if we're not exactly at the end\n return _offset == _vin.length;\n }\n\n /// @notice Checks that the vout passed up is properly formatted\n /// @dev Consider a vout with a valid scriptpubkey\n /// @param _vout Raw bytes length-prefixed output vector\n /// @return True if it represents a validly formatted vout\n function validateVout(bytes memory _vout) internal pure returns (bool) {\n uint256 _varIntDataLen;\n uint256 _nOuts;\n\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\n\n // Not valid if it says there are too many or no outputs\n if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) {\n return false;\n }\n\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 i = 0; i < _nOuts; i++) {\n // If we're at the end, but still expect more\n if (_offset >= _vout.length) {\n return false;\n }\n\n // Grab the next output and determine its length.\n // Increase the offset by that much\n uint256 _nextLen = determineOutputLengthAt(_vout, _offset);\n if (_nextLen == ERR_BAD_ARG) {\n return false;\n }\n\n _offset += _nextLen;\n }\n\n // Returns false if we're not exactly at the end\n return _offset == _vout.length;\n }\n\n\n\n /* ************ */\n /* Block Header */\n /* ************ */\n\n /// @notice Extracts the transaction merkle root from a block header\n /// @dev Use verifyHash256Merkle to verify proofs with this root\n /// @param _header The header\n /// @return The merkle root (little-endian)\n function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes32) {\n return _header.slice32(36);\n }\n\n /// @notice Extracts the target from a block header\n /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\n /// @param _header The header\n /// @return The target threshold\n function extractTarget(bytes memory _header) internal pure returns (uint256) {\n return extractTargetAt(_header, 0);\n }\n\n /// @notice Extracts the target from a block header\n /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\n /// @param _header The array containing the header\n /// @param at The start of the header\n /// @return The target threshold\n function extractTargetAt(bytes memory _header, uint256 at) internal pure returns (uint256) {\n uint24 _m = uint24(_header.slice3(72 + at));\n uint8 _e = uint8(_header[75 + at]);\n uint256 _mantissa = uint256(reverseUint24(_m));\n uint _exponent = _e - 3;\n\n return _mantissa * (256 ** _exponent);\n }\n\n /// @notice Calculate difficulty from the difficulty 1 target and current target\n /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet\n /// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\n /// @param _target The current target\n /// @return The block difficulty (bdiff)\n function calculateDifficulty(uint256 _target) internal pure returns (uint256) {\n // Difficulty 1 calculated from 0x1d00ffff\n return DIFF1_TARGET.div(_target);\n }\n\n /// @notice Extracts the previous block's hash from a block header\n /// @dev Block headers do NOT include block number :(\n /// @param _header The header\n /// @return The previous block's hash (little-endian)\n function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes32) {\n return _header.slice32(4);\n }\n\n /// @notice Extracts the previous block's hash from a block header\n /// @dev Block headers do NOT include block number :(\n /// @param _header The array containing the header\n /// @param at The start of the header\n /// @return The previous block's hash (little-endian)\n function extractPrevBlockLEAt(\n bytes memory _header,\n uint256 at\n ) internal pure returns (bytes32) {\n return _header.slice32(4 + at);\n }\n\n /// @notice Extracts the timestamp from a block header\n /// @dev Time is not 100% reliable\n /// @param _header The header\n /// @return The timestamp (little-endian bytes)\n function extractTimestampLE(bytes memory _header) internal pure returns (bytes4) {\n return _header.slice4(68);\n }\n\n /// @notice Extracts the timestamp from a block header\n /// @dev Time is not 100% reliable\n /// @param _header The header\n /// @return The timestamp (uint)\n function extractTimestamp(bytes memory _header) internal pure returns (uint32) {\n return reverseUint32(uint32(extractTimestampLE(_header)));\n }\n\n /// @notice Extracts the expected difficulty from a block header\n /// @dev Does NOT verify the work\n /// @param _header The header\n /// @return The difficulty as an integer\n function extractDifficulty(bytes memory _header) internal pure returns (uint256) {\n return calculateDifficulty(extractTarget(_header));\n }\n\n /// @notice Concatenates and hashes two inputs for merkle proving\n /// @param _a The first hash\n /// @param _b The second hash\n /// @return The double-sha256 of the concatenated hashes\n function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal view returns (bytes32) {\n return hash256View(abi.encodePacked(_a, _b));\n }\n\n /// @notice Concatenates and hashes two inputs for merkle proving\n /// @param _a The first hash\n /// @param _b The second hash\n /// @return The double-sha256 of the concatenated hashes\n function _hash256MerkleStep(bytes32 _a, bytes32 _b) internal view returns (bytes32) {\n return hash256Pair(_a, _b);\n }\n\n\n /// @notice Verifies a Bitcoin-style merkle tree\n /// @dev Leaves are 0-indexed. Inefficient version.\n /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root\n /// @param _index The index of the leaf\n /// @return true if the proof is valid, else false\n function verifyHash256Merkle(bytes memory _proof, uint _index) internal view returns (bool) {\n // Not an even number of hashes\n if (_proof.length % 32 != 0) {\n return false;\n }\n\n // Special case for coinbase-only blocks\n if (_proof.length == 32) {\n return true;\n }\n\n // Should never occur\n if (_proof.length == 64) {\n return false;\n }\n\n bytes32 _root = _proof.slice32(_proof.length - 32);\n bytes32 _current = _proof.slice32(0);\n bytes memory _tree = _proof.slice(32, _proof.length - 64);\n\n return verifyHash256Merkle(_current, _tree, _root, _index);\n }\n\n /// @notice Verifies a Bitcoin-style merkle tree\n /// @dev Leaves are 0-indexed. Efficient version.\n /// @param _leaf The leaf of the proof. LE sha256 hash.\n /// @param _tree The intermediate nodes in the proof.\n /// Tightly packed LE sha256 hashes.\n /// @param _root The root of the proof. LE sha256 hash.\n /// @param _index The index of the leaf\n /// @return true if the proof is valid, else false\n function verifyHash256Merkle(\n bytes32 _leaf,\n bytes memory _tree,\n bytes32 _root,\n uint _index\n ) internal view returns (bool) {\n // Not an even number of hashes\n if (_tree.length % 32 != 0) {\n return false;\n }\n\n // Should never occur\n if (_tree.length == 0) {\n return false;\n }\n\n uint _idx = _index;\n bytes32 _current = _leaf;\n\n // i moves in increments of 32\n for (uint i = 0; i < _tree.length; i += 32) {\n if (_idx % 2 == 1) {\n _current = _hash256MerkleStep(_tree.slice32(i), _current);\n } else {\n _current = _hash256MerkleStep(_current, _tree.slice32(i));\n }\n _idx = _idx >> 1;\n }\n return _current == _root;\n }\n\n /*\n NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72\n NB: We get a full-bitlength target from this. For comparison with\n header-encoded targets we need to mask it with the header target\n e.g. (full & truncated) == truncated\n */\n /// @notice performs the bitcoin difficulty retarget\n /// @dev implements the Bitcoin algorithm precisely\n /// @param _previousTarget the target of the previous period\n /// @param _firstTimestamp the timestamp of the first block in the difficulty period\n /// @param _secondTimestamp the timestamp of the last block in the difficulty period\n /// @return the new period's target threshold\n function retargetAlgorithm(\n uint256 _previousTarget,\n uint256 _firstTimestamp,\n uint256 _secondTimestamp\n ) internal pure returns (uint256) {\n uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);\n\n // Normalize ratio to factor of 4 if very long or very short\n if (_elapsedTime < RETARGET_PERIOD.div(4)) {\n _elapsedTime = RETARGET_PERIOD.div(4);\n }\n if (_elapsedTime > RETARGET_PERIOD.mul(4)) {\n _elapsedTime = RETARGET_PERIOD.mul(4);\n }\n\n /*\n NB: high targets e.g. ffff0020 can cause overflows here\n so we divide it by 256**2, then multiply by 256**2 later\n we know the target is evenly divisible by 256**2, so this isn't an issue\n */\n\n uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);\n return _adjusted.div(RETARGET_PERIOD).mul(65536);\n }\n}\n" - }, - "@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol": { - "content": "pragma solidity ^0.8.4;\n\n/*\n\nhttps://github.com/GNSPS/solidity-bytes-utils/\n\nThis is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, compile, sell, or\ndistribute this software, either in source code form or as a compiled\nbinary, for any purpose, commercial or non-commercial, and by any\nmeans.\n\nIn jurisdictions that recognize copyright laws, the author or authors\nof this software dedicate any and all copyright interest in the\nsoftware to the public domain. We make this dedication for the benefit\nof the public at large and to the detriment of our heirs and\nsuccessors. We intend this dedication to be an overt act of\nrelinquishment in perpetuity of all present and future rights to this\nsoftware under copyright law.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n\nFor more information, please refer to \n*/\n\n\n/** @title BytesLib **/\n/** @author https://github.com/GNSPS **/\n\nlibrary BytesLib {\n function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {\n bytes memory tempBytes;\n\n assembly {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // Store the length of the first bytes array at the beginning of\n // the memory for tempBytes.\n let length := mload(_preBytes)\n mstore(tempBytes, length)\n\n // Maintain a memory counter for the current write location in the\n // temp bytes array by adding the 32 bytes for the array length to\n // the starting location.\n let mc := add(tempBytes, 0x20)\n // Stop copying when the memory counter reaches the length of the\n // first bytes array.\n let end := add(mc, length)\n\n for {\n // Initialize a copy counter to the start of the _preBytes data,\n // 32 bytes into its memory.\n let cc := add(_preBytes, 0x20)\n } lt(mc, end) {\n // Increase both counters by 32 bytes each iteration.\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // Write the _preBytes data into the tempBytes memory 32 bytes\n // at a time.\n mstore(mc, mload(cc))\n }\n\n // Add the length of _postBytes to the current length of tempBytes\n // and store it as the new length in the first 32 bytes of the\n // tempBytes memory.\n length := mload(_postBytes)\n mstore(tempBytes, add(length, mload(tempBytes)))\n\n // Move the memory counter back from a multiple of 0x20 to the\n // actual end of the _preBytes data.\n mc := end\n // Stop copying when the memory counter reaches the new combined\n // length of the arrays.\n end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n // Update the free-memory pointer by padding our last write location\n // to 32 bytes: add 31 bytes to the end of tempBytes to move to the\n // next 32 byte block, then round down to the nearest multiple of\n // 32. If the sum of the length of the two arrays is zero then add\n // one before rounding down to leave a blank 32 bytes (the length block with 0).\n mstore(0x40, and(\n add(add(end, iszero(add(length, mload(_preBytes)))), 31),\n not(31) // Round down to the nearest 32 bytes.\n ))\n }\n\n return tempBytes;\n }\n\n function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {\n assembly {\n // Read the first 32 bytes of _preBytes storage, which is the length\n // of the array. (We don't need to use the offset into the slot\n // because arrays use the entire slot.)\n let fslot := sload(_preBytes.slot)\n // Arrays of 31 bytes or less have an even value in their slot,\n // while longer arrays have an odd value. The actual length is\n // the slot divided by two for odd values, and the lowest order\n // byte divided by two for even values.\n // If the slot is even, bitwise and the slot with 255 and divide by\n // two to get the length. If the slot is odd, bitwise and the slot\n // with -1 and divide by two.\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n let newlength := add(slength, mlength)\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n switch add(lt(slength, 32), lt(newlength, 32))\n case 2 {\n // Since the new array still fits in the slot, we just need to\n // update the contents of the slot.\n // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length\n sstore(\n _preBytes.slot,\n // all the modifications to the slot are inside this\n // next block\n add(\n // we can just add to the slot contents because the\n // bytes we want to change are the LSBs\n fslot,\n add(\n mul(\n div(\n // load the bytes from memory\n mload(add(_postBytes, 0x20)),\n // zero all bytes to the right\n exp(0x100, sub(32, mlength))\n ),\n // and now shift left the number of bytes to\n // leave space for the length in the slot\n exp(0x100, sub(32, newlength))\n ),\n // increase length by the double of the memory\n // bytes length\n mul(mlength, 2)\n )\n )\n )\n }\n case 1 {\n // The stored value fits in the slot, but the combined value\n // will exceed it.\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // The contents of the _postBytes array start 32 bytes into\n // the structure. Our first read should obtain the `submod`\n // bytes that can fit into the unused space in the last word\n // of the stored array. To get this, we read 32 bytes starting\n // from `submod`, so the data we read overlaps with the array\n // contents by `submod` bytes. Masking the lowest-order\n // `submod` bytes allows us to add that value directly to the\n // stored value.\n\n let submod := sub(32, slength)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(\n sc,\n add(\n and(\n fslot,\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00\n ),\n and(mload(mc), mask)\n )\n )\n\n for {\n mc := add(mc, 0x20)\n sc := add(sc, 1)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n default {\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n // Start copying to the last used word of the stored array.\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // Copy over the first `submod` bytes of the new data as in\n // case 1 above.\n let slengthmod := mod(slength, 32)\n let mlengthmod := mod(mlength, 32)\n let submod := sub(32, slengthmod)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(sc, add(sload(sc), and(mload(mc), mask)))\n\n for {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n }\n }\n\n function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) {\n if (_length == 0) {\n return hex\"\";\n }\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n // Alloc bytes array with additional 32 bytes afterspace and assign it's size\n res := mload(0x40)\n mstore(0x40, add(add(res, 64), _length))\n mstore(res, _length)\n\n // Compute distance between source and destination pointers\n let diff := sub(res, add(_bytes, _start))\n\n for {\n let src := add(add(_bytes, 32), _start)\n let end := add(src, _length)\n } lt(src, end) {\n src := add(src, 32)\n } {\n mstore(add(src, diff), mload(src))\n }\n }\n }\n\n /// @notice Take a slice of the byte array, overwriting the destination.\n /// The length of the slice will equal the length of the destination array.\n /// @dev Make sure the destination array has afterspace if required.\n /// @param _bytes The source array\n /// @param _dest The destination array.\n /// @param _start The location to start in the source array.\n function sliceInPlace(\n bytes memory _bytes,\n bytes memory _dest,\n uint _start\n ) internal pure {\n uint _length = _dest.length;\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n for {\n let src := add(add(_bytes, 32), _start)\n let res := add(_dest, 32)\n let end := add(src, _length)\n } lt(src, end) {\n src := add(src, 32)\n res := add(res, 32)\n } {\n mstore(res, mload(src))\n }\n }\n }\n\n // Static slice functions, no bounds checking\n /// @notice take a 32-byte slice from the specified position\n function slice32(bytes memory _bytes, uint _start) internal pure returns (bytes32 res) {\n assembly {\n res := mload(add(add(_bytes, 32), _start))\n }\n }\n\n /// @notice take a 20-byte slice from the specified position\n function slice20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {\n return bytes20(slice32(_bytes, _start));\n }\n\n /// @notice take a 8-byte slice from the specified position\n function slice8(bytes memory _bytes, uint _start) internal pure returns (bytes8) {\n return bytes8(slice32(_bytes, _start));\n }\n\n /// @notice take a 4-byte slice from the specified position\n function slice4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {\n return bytes4(slice32(_bytes, _start));\n }\n\n /// @notice take a 3-byte slice from the specified position\n function slice3(bytes memory _bytes, uint _start) internal pure returns (bytes3) {\n return bytes3(slice32(_bytes, _start));\n }\n\n /// @notice take a 2-byte slice from the specified position\n function slice2(bytes memory _bytes, uint _start) internal pure returns (bytes2) {\n return bytes2(slice32(_bytes, _start));\n }\n\n function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {\n uint _totalLen = _start + 20;\n require(_totalLen > _start && _bytes.length >= _totalLen, \"Address conversion out of bounds.\");\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {\n uint _totalLen = _start + 32;\n require(_totalLen > _start && _bytes.length >= _totalLen, \"Uint conversion out of bounds.\");\n uint256 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x20), _start))\n }\n\n return tempUint;\n }\n\n function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {\n bool success = true;\n\n assembly {\n let length := mload(_preBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(length, mload(_postBytes))\n case 1 {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n let mc := add(_preBytes, 0x20)\n let end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n // the next line is the loop condition:\n // while(uint(mc < end) + cb == 2)\n } eq(add(lt(mc, end), cb), 2) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // if any of these checks fails then arrays are not equal\n if iszero(eq(mload(mc), mload(cc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {\n bool success = true;\n\n assembly {\n // we know _preBytes_offset is 0\n let fslot := sload(_preBytes.slot)\n // Decode the length of the stored array like in concatStorage().\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(slength, mlength)\n case 1 {\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n if iszero(iszero(slength)) {\n switch lt(slength, 32)\n case 1 {\n // blank the last byte which is the length\n fslot := mul(div(fslot, 0x100), 0x100)\n\n if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {\n // unsuccess:\n success := 0\n }\n }\n default {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := keccak256(0x0, 0x20)\n\n let mc := add(_postBytes, 0x20)\n let end := add(mc, mlength)\n\n // the next line is the loop condition:\n // while(uint(mc < end) + cb == 2)\n for {} eq(add(lt(mc, end), cb), 2) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n if iszero(eq(sload(sc), mload(mc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function toBytes32(bytes memory _source) pure internal returns (bytes32 result) {\n if (_source.length == 0) {\n return 0x0;\n }\n\n assembly {\n result := mload(add(_source, 32))\n }\n }\n\n function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) {\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n result := keccak256(add(add(_bytes, 32), _start), _length)\n }\n }\n}\n" - }, - "@keep-network/bitcoin-spv-sol/contracts/SafeMath.sol": { - "content": "pragma solidity ^0.8.4;\n\n/*\nThe MIT License (MIT)\n\nCopyright (c) 2016 Smart Contract Solutions, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n\n/**\n * @title SafeMath\n * @dev Math operations with safety checks that throw on error\n */\nlibrary SafeMath {\n\n /**\n * @dev Multiplies two numbers, throws on overflow.\n */\n function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\n // Gas optimization: this is cheaper than asserting 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\n if (_a == 0) {\n return 0;\n }\n\n c = _a * _b;\n require(c / _a == _b, \"Overflow during multiplication.\");\n return c;\n }\n\n /**\n * @dev Integer division of two numbers, truncating the quotient.\n */\n function div(uint256 _a, uint256 _b) internal pure returns (uint256) {\n // assert(_b > 0); // Solidity automatically throws when dividing by 0\n // uint256 c = _a / _b;\n // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold\n return _a / _b;\n }\n\n /**\n * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).\n */\n function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {\n require(_b <= _a, \"Underflow during subtraction.\");\n return _a - _b;\n }\n\n /**\n * @dev Adds two numbers, throws on overflow.\n */\n function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\n c = _a + _b;\n require(c >= _a, \"Overflow during addition.\");\n return c;\n }\n}\n" - }, - "@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.0;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\n\nimport \"./IBridge.sol\";\nimport \"./ITBTCVault.sol\";\n\n/// @title Abstract AbstractTBTCDepositor contract.\n/// @notice This abstract contract is meant to facilitate integration of protocols\n/// aiming to use tBTC as an underlying Bitcoin bridge.\n///\n/// Such an integrator is supposed to:\n/// - Create a child contract inheriting from this abstract contract\n/// - Call the `__AbstractTBTCDepositor_initialize` initializer function\n/// - Use the `_initializeDeposit` and `_finalizeDeposit` as part of their\n/// business logic in order to initialize and finalize deposits.\n///\n/// @dev Example usage:\n/// ```\n/// // Example upgradeable integrator contract.\n/// contract ExampleTBTCIntegrator is AbstractTBTCDepositor, Initializable {\n/// /// @custom:oz-upgrades-unsafe-allow constructor\n/// constructor() {\n/// // Prevents the contract from being initialized again.\n/// _disableInitializers();\n/// }\n///\n/// function initialize(\n/// address _bridge,\n/// address _tbtcVault\n/// ) external initializer {\n/// __AbstractTBTCDepositor_initialize(_bridge, _tbtcVault);\n/// }\n///\n/// function startProcess(\n/// IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n/// IBridgeTypes.DepositRevealInfo calldata reveal\n/// ) external {\n/// // Embed necessary context as extra data.\n/// bytes32 extraData = ...;\n///\n/// uint256 depositKey = _initializeDeposit(\n/// fundingTx,\n/// reveal,\n/// extraData\n/// );\n///\n/// // Use the depositKey to track the process.\n/// }\n///\n/// function finalizeProcess(uint256 depositKey) external {\n/// // Ensure the function cannot be called for the same deposit\n/// // twice.\n///\n/// (\n/// uint256 initialDepositAmount,\n/// uint256 tbtcAmount,\n/// bytes32 extraData\n/// ) = _finalizeDeposit(depositKey);\n///\n/// // Do something with the minted TBTC using context\n/// // embedded in the extraData.\n/// }\n/// }\nabstract contract AbstractTBTCDepositor {\n using BTCUtils for bytes;\n\n /// @notice Multiplier to convert satoshi to TBTC token units.\n uint256 public constant SATOSHI_MULTIPLIER = 10**10;\n\n /// @notice Bridge contract address.\n IBridge public bridge;\n /// @notice TBTCVault contract address.\n ITBTCVault public tbtcVault;\n\n // Reserved storage space that allows adding more variables without affecting\n // the storage layout of the child contracts. The convention from OpenZeppelin\n // suggests the storage space should add up to 50 slots. If more variables are\n // added in the upcoming versions one need to reduce the array size accordingly.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[47] private __gap;\n\n event DepositInitialized(uint256 indexed depositKey, uint32 initializedAt);\n\n event DepositFinalized(\n uint256 indexed depositKey,\n uint256 tbtcAmount,\n uint32 finalizedAt\n );\n\n /// @notice Initializes the contract. MUST BE CALLED from the child\n /// contract initializer.\n // slither-disable-next-line dead-code\n function __AbstractTBTCDepositor_initialize(\n address _bridge,\n address _tbtcVault\n ) internal {\n require(\n address(bridge) == address(0) && address(tbtcVault) == address(0),\n \"AbstractTBTCDepositor already initialized\"\n );\n\n require(_bridge != address(0), \"Bridge address cannot be zero\");\n require(_tbtcVault != address(0), \"TBTCVault address cannot be zero\");\n\n bridge = IBridge(_bridge);\n tbtcVault = ITBTCVault(_tbtcVault);\n }\n\n /// @notice Initializes a deposit by revealing it to the Bridge.\n /// @param fundingTx Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.\n /// @param reveal Deposit reveal data, see `IBridgeTypes.DepositRevealInfo` struct.\n /// @param extraData 32-byte deposit extra data.\n /// @return depositKey Deposit key computed as\n /// `keccak256(fundingTxHash | reveal.fundingOutputIndex)`. This\n /// key can be used to refer to the deposit in the Bridge and\n /// TBTCVault contracts.\n /// @dev Requirements:\n /// - The revealed vault address must match the TBTCVault address,\n /// - All requirements from {Bridge#revealDepositWithExtraData}\n /// function must be met.\n /// @dev This function doesn't validate if a deposit has been initialized before,\n /// as the Bridge won't allow the same deposit to be revealed twice.\n // slither-disable-next-line dead-code\n function _initializeDeposit(\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n IBridgeTypes.DepositRevealInfo calldata reveal,\n bytes32 extraData\n ) internal returns (uint256) {\n require(reveal.vault == address(tbtcVault), \"Vault address mismatch\");\n\n uint256 depositKey = _calculateDepositKey(\n _calculateBitcoinTxHash(fundingTx),\n reveal.fundingOutputIndex\n );\n\n emit DepositInitialized(\n depositKey,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp)\n );\n\n // The Bridge does not allow to reveal the same deposit twice and\n // revealed deposits stay there forever. The transaction will revert\n // if the deposit has already been revealed so, there is no need to do\n // an explicit check here.\n bridge.revealDepositWithExtraData(fundingTx, reveal, extraData);\n\n return depositKey;\n }\n\n /// @notice Finalizes a deposit by calculating the amount of TBTC minted\n /// for the deposit.\n /// @param depositKey Deposit key identifying the deposit.\n /// @return initialDepositAmount Amount of funding transaction deposit. In\n /// TBTC token decimals precision.\n /// @return tbtcAmount Approximate amount of TBTC minted for the deposit. In\n /// TBTC token decimals precision.\n /// @return extraData 32-byte deposit extra data.\n /// @dev Requirements:\n /// - The deposit must be initialized but not finalized\n /// (in the context of this contract) yet.\n /// - The deposit must be finalized on the Bridge side. That means the\n /// deposit must be either swept or optimistically minted.\n /// @dev THIS FUNCTION DOESN'T VALIDATE IF A DEPOSIT HAS BEEN FINALIZED BEFORE,\n /// IT IS A RESPONSIBILITY OF THE IMPLEMENTING CONTRACT TO ENSURE THIS\n /// FUNCTION WON'T BE CALLED TWICE FOR THE SAME DEPOSIT.\n /// @dev IMPORTANT NOTE: The tbtcAmount returned by this function is an\n /// approximation. See documentation of the `calculateTbtcAmount`\n /// responsible for calculating this value for more details.\n // slither-disable-next-line dead-code\n function _finalizeDeposit(uint256 depositKey)\n internal\n returns (\n uint256 initialDepositAmount,\n uint256 tbtcAmount,\n bytes32 extraData\n )\n {\n IBridgeTypes.DepositRequest memory deposit = bridge.deposits(\n depositKey\n );\n require(deposit.revealedAt != 0, \"Deposit not initialized\");\n\n (, uint64 finalizedAt) = tbtcVault.optimisticMintingRequests(\n depositKey\n );\n\n require(\n deposit.sweptAt != 0 || finalizedAt != 0,\n \"Deposit not finalized by the bridge\"\n );\n\n initialDepositAmount = deposit.amount * SATOSHI_MULTIPLIER;\n\n tbtcAmount = _calculateTbtcAmount(deposit.amount, deposit.treasuryFee);\n\n // slither-disable-next-line reentrancy-events\n emit DepositFinalized(\n depositKey,\n tbtcAmount,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp)\n );\n\n extraData = deposit.extraData;\n }\n\n /// @notice Calculates the amount of TBTC minted for the deposit.\n /// @param depositAmountSat Deposit amount in satoshi (1e8 precision).\n /// This is the actual amount deposited by the deposit creator, i.e.\n /// the gross amount the Bridge's fees are cut from.\n /// @param depositTreasuryFeeSat Deposit treasury fee in satoshi (1e8 precision).\n /// This is an accurate value of the treasury fee that was actually\n /// cut upon minting.\n /// @return tbtcAmount Approximate amount of TBTC minted for the deposit.\n /// @dev IMPORTANT NOTE: The tbtcAmount returned by this function may\n /// not correspond to the actual amount of TBTC minted for the deposit.\n /// Although the treasury fee cut upon minting is known precisely,\n /// this is not the case for the optimistic minting fee and the Bitcoin\n /// transaction fee. To overcome that problem, this function just takes\n /// the current maximum allowed values of both fees, at the moment of deposit\n /// finalization. For the great majority of the deposits, such an\n /// algorithm will return a tbtcAmount slightly lesser than the\n /// actual amount of TBTC minted for the deposit. This will cause\n /// some TBTC to be left in the contract and ensure there is enough\n /// liquidity to finalize the deposit. However, in some rare cases,\n /// where the actual values of those fees change between the deposit\n /// minting and finalization, the tbtcAmount returned by this function\n /// may be greater than the actual amount of TBTC minted for the deposit.\n /// If this happens and the reserve coming from previous deposits\n /// leftovers does not provide enough liquidity, the deposit will have\n /// to wait for finalization until the reserve is refilled by subsequent\n /// deposits or a manual top-up. The integrator is responsible for\n /// handling such cases.\n // slither-disable-next-line dead-code\n function _calculateTbtcAmount(\n uint64 depositAmountSat,\n uint64 depositTreasuryFeeSat\n ) internal view virtual returns (uint256) {\n // Both deposit amount and treasury fee are in the 1e8 satoshi precision.\n // We need to convert them to the 1e18 TBTC precision.\n uint256 amountSubTreasury = (depositAmountSat - depositTreasuryFeeSat) *\n SATOSHI_MULTIPLIER;\n\n uint256 omFeeDivisor = tbtcVault.optimisticMintingFeeDivisor();\n uint256 omFee = omFeeDivisor > 0\n ? (amountSubTreasury / omFeeDivisor)\n : 0;\n\n // The deposit transaction max fee is in the 1e8 satoshi precision.\n // We need to convert them to the 1e18 TBTC precision.\n (, , uint64 depositTxMaxFee, ) = bridge.depositParameters();\n uint256 txMaxFee = depositTxMaxFee * SATOSHI_MULTIPLIER;\n\n return amountSubTreasury - omFee - txMaxFee;\n }\n\n /// @notice Calculates the deposit key for the given funding transaction\n /// hash and funding output index.\n /// @param fundingTxHash Funding transaction hash.\n /// @param fundingOutputIndex Funding output index.\n /// @return depositKey Deposit key computed as\n /// `keccak256(fundingTxHash | reveal.fundingOutputIndex)`. This\n /// key can be used to refer to the deposit in the Bridge and\n /// TBTCVault contracts.\n // slither-disable-next-line dead-code\n function _calculateDepositKey(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex\n ) internal pure returns (uint256) {\n return\n uint256(\n keccak256(abi.encodePacked(fundingTxHash, fundingOutputIndex))\n );\n }\n\n /// @notice Calculates the Bitcoin transaction hash for the given Bitcoin\n /// transaction data.\n /// @param txInfo Bitcoin transaction data, see `IBridgeTypes.BitcoinTxInfo` struct.\n /// @return txHash Bitcoin transaction hash.\n // slither-disable-next-line dead-code\n function _calculateBitcoinTxHash(IBridgeTypes.BitcoinTxInfo calldata txInfo)\n internal\n view\n returns (bytes32)\n {\n return\n abi\n .encodePacked(\n txInfo.version,\n txInfo.inputVector,\n txInfo.outputVector,\n txInfo.locktime\n )\n .hash256View();\n }\n}\n" - }, - "@keep-network/tbtc-v2/contracts/integrator/IBridge.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.0;\n\n/// @notice Namespace which groups all types relevant to the IBridge interface.\n/// @dev This is a mirror of the real types used in the Bridge contract.\n/// This way, the `integrator` subpackage does not need to import\n/// anything from the `bridge` subpackage and explicitly depend on it.\n/// This simplifies the dependency graph for integrators.\nlibrary IBridgeTypes {\n /// @dev See bridge/BitcoinTx.sol#Info\n struct BitcoinTxInfo {\n bytes4 version;\n bytes inputVector;\n bytes outputVector;\n bytes4 locktime;\n }\n\n /// @dev See bridge/Deposit.sol#DepositRevealInfo\n struct DepositRevealInfo {\n uint32 fundingOutputIndex;\n bytes8 blindingFactor;\n bytes20 walletPubKeyHash;\n bytes20 refundPubKeyHash;\n bytes4 refundLocktime;\n address vault;\n }\n\n /// @dev See bridge/Deposit.sol#DepositRequest\n struct DepositRequest {\n address depositor;\n uint64 amount;\n uint32 revealedAt;\n address vault;\n uint64 treasuryFee;\n uint32 sweptAt;\n bytes32 extraData;\n }\n}\n\n/// @notice Interface of the Bridge contract.\n/// @dev See bridge/Bridge.sol\ninterface IBridge {\n /// @dev See {Bridge#revealDepositWithExtraData}\n function revealDepositWithExtraData(\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n IBridgeTypes.DepositRevealInfo calldata reveal,\n bytes32 extraData\n ) external;\n\n /// @dev See {Bridge#deposits}\n function deposits(uint256 depositKey)\n external\n view\n returns (IBridgeTypes.DepositRequest memory);\n\n /// @dev See {Bridge#depositParameters}\n function depositParameters()\n external\n view\n returns (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n );\n}\n" - }, - "@keep-network/tbtc-v2/contracts/integrator/ITBTCVault.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.0;\n\n/// @notice Interface of the TBTCVault contract.\n/// @dev See vault/TBTCVault.sol\ninterface ITBTCVault {\n /// @dev See {TBTCVault#optimisticMintingRequests}\n function optimisticMintingRequests(uint256 depositKey)\n external\n returns (uint64 requestedAt, uint64 finalizedAt);\n\n /// @dev See {TBTCVault#optimisticMintingFeeDivisor}\n function optimisticMintingFeeDivisor() external view returns (uint32);\n}\n" - }, - "@keep-network/tbtc-v2/contracts/test/TestTBTCDepositor.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity ^0.8.0;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\n\nimport \"../integrator/AbstractTBTCDepositor.sol\";\nimport \"../integrator/IBridge.sol\";\nimport \"../integrator/ITBTCVault.sol\";\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract TestTBTCDepositor is AbstractTBTCDepositor {\n event InitializeDepositReturned(uint256 depositKey);\n\n event FinalizeDepositReturned(\n uint256 initialDepositAmount,\n uint256 tbtcAmount,\n bytes32 extraData\n );\n\n function initialize(address _bridge, address _tbtcVault) external {\n __AbstractTBTCDepositor_initialize(_bridge, _tbtcVault);\n }\n\n function initializeDepositPublic(\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n IBridgeTypes.DepositRevealInfo calldata reveal,\n bytes32 extraData\n ) external {\n uint256 depositKey = _initializeDeposit(fundingTx, reveal, extraData);\n emit InitializeDepositReturned(depositKey);\n }\n\n function finalizeDepositPublic(uint256 depositKey) external {\n (\n uint256 initialDepositAmount,\n uint256 tbtcAmount,\n bytes32 extraData\n ) = _finalizeDeposit(depositKey);\n emit FinalizeDepositReturned(\n initialDepositAmount,\n tbtcAmount,\n extraData\n );\n }\n\n function calculateTbtcAmountPublic(\n uint64 depositAmountSat,\n uint64 depositTreasuryFeeSat\n ) external view returns (uint256) {\n return _calculateTbtcAmount(depositAmountSat, depositTreasuryFeeSat);\n }\n}\n\ncontract MockBridge is IBridge {\n using BTCUtils for bytes;\n\n mapping(uint256 => IBridgeTypes.DepositRequest) internal _deposits;\n\n uint64 internal _depositTreasuryFeeDivisor = 50; // 1/50 == 100 bps == 2% == 0.02\n uint64 internal _depositTxMaxFee = 1000; // 1000 satoshi = 0.00001 BTC\n\n event DepositRevealed(uint256 depositKey);\n\n function revealDepositWithExtraData(\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n IBridgeTypes.DepositRevealInfo calldata reveal,\n bytes32 extraData\n ) external {\n bytes32 fundingTxHash = abi\n .encodePacked(\n fundingTx.version,\n fundingTx.inputVector,\n fundingTx.outputVector,\n fundingTx.locktime\n )\n .hash256View();\n\n uint256 depositKey = uint256(\n keccak256(\n abi.encodePacked(fundingTxHash, reveal.fundingOutputIndex)\n )\n );\n\n require(\n _deposits[depositKey].revealedAt == 0,\n \"Deposit already revealed\"\n );\n\n bytes memory fundingOutput = fundingTx\n .outputVector\n .extractOutputAtIndex(reveal.fundingOutputIndex);\n\n uint64 fundingOutputAmount = fundingOutput.extractValue();\n\n IBridgeTypes.DepositRequest memory request;\n\n request.depositor = msg.sender;\n request.amount = fundingOutputAmount;\n /* solhint-disable-next-line not-rely-on-time */\n request.revealedAt = uint32(block.timestamp);\n request.vault = reveal.vault;\n request.treasuryFee = _depositTreasuryFeeDivisor > 0\n ? fundingOutputAmount / _depositTreasuryFeeDivisor\n : 0;\n request.sweptAt = 0;\n request.extraData = extraData;\n\n _deposits[depositKey] = request;\n\n emit DepositRevealed(depositKey);\n }\n\n function sweepDeposit(uint256 depositKey) public {\n require(_deposits[depositKey].revealedAt != 0, \"Deposit not revealed\");\n require(_deposits[depositKey].sweptAt == 0, \"Deposit already swept\");\n /* solhint-disable-next-line not-rely-on-time */\n _deposits[depositKey].sweptAt = uint32(block.timestamp);\n }\n\n function deposits(uint256 depositKey)\n external\n view\n returns (IBridgeTypes.DepositRequest memory)\n {\n return _deposits[depositKey];\n }\n\n function depositParameters()\n external\n view\n returns (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n )\n {\n depositDustThreshold = 0;\n depositTreasuryFeeDivisor = 0;\n depositTxMaxFee = _depositTxMaxFee;\n depositRevealAheadPeriod = 0;\n }\n\n function setDepositTreasuryFeeDivisor(uint64 value) external {\n _depositTreasuryFeeDivisor = value;\n }\n\n function setDepositTxMaxFee(uint64 value) external {\n _depositTxMaxFee = value;\n }\n}\n\ncontract MockTBTCVault is ITBTCVault {\n struct Request {\n uint64 requestedAt;\n uint64 finalizedAt;\n }\n\n mapping(uint256 => Request) internal _requests;\n\n uint32 public optimisticMintingFeeDivisor = 100; // 1%\n\n function optimisticMintingRequests(uint256 depositKey)\n external\n returns (uint64 requestedAt, uint64 finalizedAt)\n {\n Request memory request = _requests[depositKey];\n return (request.requestedAt, request.finalizedAt);\n }\n\n /// @dev The function is virtual to allow other projects using this mock\n /// for AbtractTBTCDepositor-based contract tests to add any custom\n /// logic needed.\n function createOptimisticMintingRequest(uint256 depositKey) public virtual {\n require(\n _requests[depositKey].requestedAt == 0,\n \"Request already exists\"\n );\n /* solhint-disable-next-line not-rely-on-time */\n _requests[depositKey].requestedAt = uint64(block.timestamp);\n }\n\n /// @dev The function is virtual to allow other projects using this mock\n /// for AbtractTBTCDepositor-based contract tests to add any custom\n /// logic needed.\n function finalizeOptimisticMintingRequest(uint256 depositKey)\n public\n virtual\n {\n require(\n _requests[depositKey].requestedAt != 0,\n \"Request does not exist\"\n );\n require(\n _requests[depositKey].finalizedAt == 0,\n \"Request already finalized\"\n );\n /* solhint-disable-next-line not-rely-on-time */\n _requests[depositKey].finalizedAt = uint64(block.timestamp);\n }\n\n function setOptimisticMintingFeeDivisor(uint32 value) external {\n optimisticMintingFeeDivisor = value;\n }\n}\n" - }, - "@openzeppelin/contracts/access/Ownable.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n /**\n * @dev The caller account is not authorized to perform an operation.\n */\n error OwnableUnauthorizedAccount(address account);\n\n /**\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\n */\n error OwnableInvalidOwner(address owner);\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n */\n constructor(address initialOwner) {\n if (initialOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(initialOwner);\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n if (owner() != _msgSender()) {\n revert OwnableUnauthorizedAccount(_msgSender());\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n if (newOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n" - }, - "@openzeppelin/contracts/access/Ownable2Step.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)\n\npragma solidity ^0.8.20;\n\nimport {Ownable} from \"./Ownable.sol\";\n\n/**\n * @dev Contract module which provides access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is specified at deployment time in the constructor for `Ownable`. This\n * can later be changed with {transferOwnership} and {acceptOwnership}.\n *\n * This module is used through inheritance. It will make available all functions\n * from parent (Ownable).\n */\nabstract contract Ownable2Step is Ownable {\n address private _pendingOwner;\n\n event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Returns the address of the pending owner.\n */\n function pendingOwner() public view virtual returns (address) {\n return _pendingOwner;\n }\n\n /**\n * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual override onlyOwner {\n _pendingOwner = newOwner;\n emit OwnershipTransferStarted(owner(), newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual override {\n delete _pendingOwner;\n super._transferOwnership(newOwner);\n }\n\n /**\n * @dev The new owner accepts the ownership transfer.\n */\n function acceptOwnership() public virtual {\n address sender = _msgSender();\n if (pendingOwner() != sender) {\n revert OwnableUnauthorizedAccount(sender);\n }\n _transferOwnership(sender);\n }\n}\n" - }, - "@openzeppelin/contracts/interfaces/draft-IERC6093.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard ERC20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.\n */\ninterface IERC20Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC20InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC20InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n * @param allowance Amount of tokens a `spender` is allowed to operate with.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC20InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.\n */\ninterface IERC721Errors {\n /**\n * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.\n * Used in balance queries.\n * @param owner Address of the current owner of a token.\n */\n error ERC721InvalidOwner(address owner);\n\n /**\n * @dev Indicates a `tokenId` whose `owner` is the zero address.\n * @param tokenId Identifier number of a token.\n */\n error ERC721NonexistentToken(uint256 tokenId);\n\n /**\n * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param tokenId Identifier number of a token.\n * @param owner Address of the current owner of a token.\n */\n error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC721InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC721InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param tokenId Identifier number of a token.\n */\n error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC721InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.\n */\ninterface IERC1155Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n * @param tokenId Identifier number of a token.\n */\n error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC1155InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC1155InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param owner Address of the current owner of a token.\n */\n error ERC1155MissingApprovalForAll(address operator, address owner);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC1155InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC1155InvalidOperator(address operator);\n\n /**\n * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n * Used in batch transfers.\n * @param idsLength Length of the array of token identifiers\n * @param valuesLength Length of the array of token amounts\n */\n error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n" - }, - "@openzeppelin/contracts/interfaces/IERC4626.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"../token/ERC20/extensions/IERC20Metadata.sol\";\n\n/**\n * @dev Interface of the ERC4626 \"Tokenized Vault Standard\", as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\n */\ninterface IERC4626 is IERC20, IERC20Metadata {\n event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed sender,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /**\n * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\n *\n * - MUST be an ERC-20 token contract.\n * - MUST NOT revert.\n */\n function asset() external view returns (address assetTokenAddress);\n\n /**\n * @dev Returns the total amount of the underlying asset that is “managed” by Vault.\n *\n * - SHOULD include any compounding that occurs from yield.\n * - MUST be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT revert.\n */\n function totalAssets() external view returns (uint256 totalManagedAssets);\n\n /**\n * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\n * scenario where all the conditions are met.\n *\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT show any variations depending on the caller.\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n * - MUST NOT revert.\n *\n * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n * from.\n */\n function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\n * scenario where all the conditions are met.\n *\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT show any variations depending on the caller.\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n * - MUST NOT revert.\n *\n * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n * from.\n */\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\n * through a deposit call.\n *\n * - MUST return a limited value if receiver is subject to some deposit limit.\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\n * - MUST NOT revert.\n */\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\n * current on-chain conditions.\n *\n * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\n * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\n * in the same transaction.\n * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\n * deposit would be accepted, regardless if the user has enough tokens approved, etc.\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n */\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\n *\n * - MUST emit the Deposit event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * deposit execution, and are accounted for during deposit.\n * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\n * approving enough underlying tokens to the Vault contract, etc).\n *\n * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n */\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n /**\n * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\n * - MUST return a limited value if receiver is subject to some mint limit.\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\n * - MUST NOT revert.\n */\n function maxMint(address receiver) external view returns (uint256 maxShares);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\n * current on-chain conditions.\n *\n * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\n * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\n * same transaction.\n * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\n * would be accepted, regardless if the user has enough tokens approved, etc.\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by minting.\n */\n function previewMint(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\n *\n * - MUST emit the Deposit event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\n * execution, and are accounted for during mint.\n * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\n * approving enough underlying tokens to the Vault contract, etc).\n *\n * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n */\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n /**\n * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\n * Vault, through a withdraw call.\n *\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n * - MUST NOT revert.\n */\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\n * given current on-chain conditions.\n *\n * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\n * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\n * called\n * in the same transaction.\n * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\n * the withdrawal would be accepted, regardless if the user has enough shares, etc.\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n */\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\n *\n * - MUST emit the Withdraw event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * withdraw execution, and are accounted for during withdraw.\n * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\n * not having enough shares, etc).\n *\n * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n * Those methods should be performed separately.\n */\n function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\n\n /**\n * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\n * through a redeem call.\n *\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\n * - MUST NOT revert.\n */\n function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\n * given current on-chain conditions.\n *\n * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\n * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\n * same transaction.\n * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\n * redemption would be accepted, regardless if the user has enough shares, etc.\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\n */\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\n *\n * - MUST emit the Withdraw event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * redeem execution, and are accounted for during redeem.\n * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\n * not having enough shares, etc).\n *\n * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n * Those methods should be performed separately.\n */\n function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/ERC20.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC20Metadata} from \"./extensions/IERC20Metadata.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {IERC20Errors} from \"../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n */\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\n mapping(address account => uint256) private _balances;\n\n mapping(address account => mapping(address spender => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the default value returned by this function, unless\n * it's overridden.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `value`.\n */\n function transfer(address to, uint256 value) public virtual returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, value);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 value) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, value);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `value`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `value`.\n */\n function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, value);\n _transfer(from, to, value);\n return true;\n }\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead.\n */\n function _transfer(address from, address to, uint256 value) internal {\n if (from == address(0)) {\n revert ERC20InvalidSender(address(0));\n }\n if (to == address(0)) {\n revert ERC20InvalidReceiver(address(0));\n }\n _update(from, to, value);\n }\n\n /**\n * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n * this function.\n *\n * Emits a {Transfer} event.\n */\n function _update(address from, address to, uint256 value) internal virtual {\n if (from == address(0)) {\n // Overflow check required: The rest of the code assumes that totalSupply never overflows\n _totalSupply += value;\n } else {\n uint256 fromBalance = _balances[from];\n if (fromBalance < value) {\n revert ERC20InsufficientBalance(from, fromBalance, value);\n }\n unchecked {\n // Overflow not possible: value <= fromBalance <= totalSupply.\n _balances[from] = fromBalance - value;\n }\n }\n\n if (to == address(0)) {\n unchecked {\n // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\n _totalSupply -= value;\n }\n } else {\n unchecked {\n // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n _balances[to] += value;\n }\n }\n\n emit Transfer(from, to, value);\n }\n\n /**\n * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n * Relies on the `_update` mechanism\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead.\n */\n function _mint(address account, uint256 value) internal {\n if (account == address(0)) {\n revert ERC20InvalidReceiver(address(0));\n }\n _update(address(0), account, value);\n }\n\n /**\n * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n * Relies on the `_update` mechanism.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead\n */\n function _burn(address account, uint256 value) internal {\n if (account == address(0)) {\n revert ERC20InvalidSender(address(0));\n }\n _update(account, address(0), value);\n }\n\n /**\n * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n *\n * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n */\n function _approve(address owner, address spender, uint256 value) internal {\n _approve(owner, spender, value, true);\n }\n\n /**\n * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n *\n * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\n * `Approval` event during `transferFrom` operations.\n *\n * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\n * true using the following override:\n * ```\n * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n * super._approve(owner, spender, value, true);\n * }\n * ```\n *\n * Requirements are the same as {_approve}.\n */\n function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n if (owner == address(0)) {\n revert ERC20InvalidApprover(address(0));\n }\n if (spender == address(0)) {\n revert ERC20InvalidSpender(address(0));\n }\n _allowances[owner][spender] = value;\n if (emitEvent) {\n emit Approval(owner, spender, value);\n }\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `value`.\n *\n * Does not update the allowance value in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Does not emit an {Approval} event.\n */\n function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n if (currentAllowance < value) {\n revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n }\n unchecked {\n _approve(owner, spender, currentAllowance - value, false);\n }\n }\n }\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20, IERC20Metadata, ERC20} from \"../ERC20.sol\";\nimport {SafeERC20} from \"../utils/SafeERC20.sol\";\nimport {IERC4626} from \"../../../interfaces/IERC4626.sol\";\nimport {Math} from \"../../../utils/math/Math.sol\";\n\n/**\n * @dev Implementation of the ERC4626 \"Tokenized Vault Standard\" as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].\n *\n * This extension allows the minting and burning of \"shares\" (represented using the ERC20 inheritance) in exchange for\n * underlying \"assets\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\n * the ERC20 standard. Any additional extensions included along it would affect the \"shares\" token represented by this\n * contract and not the \"assets\" token which is an independent contract.\n *\n * [CAUTION]\n * ====\n * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning\n * with a \"donation\" to the vault that inflates the price of a share. This is variously known as a donation or inflation\n * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial\n * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may\n * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by\n * verifying the amount received is as expected, using a wrapper that performs these checks such as\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\n *\n * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`\n * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault\n * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself\n * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset\n * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's\n * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more\n * expensive than it is profitable. More details about the underlying math can be found\n * xref:erc4626.adoc#inflation-attack[here].\n *\n * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued\n * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets\n * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience\n * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the\n * `_convertToShares` and `_convertToAssets` functions.\n *\n * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].\n * ====\n */\nabstract contract ERC4626 is ERC20, IERC4626 {\n using Math for uint256;\n\n IERC20 private immutable _asset;\n uint8 private immutable _underlyingDecimals;\n\n /**\n * @dev Attempted to deposit more assets than the max amount for `receiver`.\n */\n error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);\n\n /**\n * @dev Attempted to mint more shares than the max amount for `receiver`.\n */\n error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);\n\n /**\n * @dev Attempted to withdraw more assets than the max amount for `receiver`.\n */\n error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);\n\n /**\n * @dev Attempted to redeem more shares than the max amount for `receiver`.\n */\n error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);\n\n /**\n * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).\n */\n constructor(IERC20 asset_) {\n (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\n _underlyingDecimals = success ? assetDecimals : 18;\n _asset = asset_;\n }\n\n /**\n * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\n */\n function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {\n (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(\n abi.encodeCall(IERC20Metadata.decimals, ())\n );\n if (success && encodedDecimals.length >= 32) {\n uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));\n if (returnedDecimals <= type(uint8).max) {\n return (true, uint8(returnedDecimals));\n }\n }\n return (false, 0);\n }\n\n /**\n * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This\n * \"original\" value is cached during construction of the vault contract. If this read operation fails (e.g., the\n * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.\n *\n * See {IERC20Metadata-decimals}.\n */\n function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {\n return _underlyingDecimals + _decimalsOffset();\n }\n\n /** @dev See {IERC4626-asset}. */\n function asset() public view virtual returns (address) {\n return address(_asset);\n }\n\n /** @dev See {IERC4626-totalAssets}. */\n function totalAssets() public view virtual returns (uint256) {\n return _asset.balanceOf(address(this));\n }\n\n /** @dev See {IERC4626-convertToShares}. */\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _convertToShares(assets, Math.Rounding.Floor);\n }\n\n /** @dev See {IERC4626-convertToAssets}. */\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _convertToAssets(shares, Math.Rounding.Floor);\n }\n\n /** @dev See {IERC4626-maxDeposit}. */\n function maxDeposit(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n /** @dev See {IERC4626-maxMint}. */\n function maxMint(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n /** @dev See {IERC4626-maxWithdraw}. */\n function maxWithdraw(address owner) public view virtual returns (uint256) {\n return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);\n }\n\n /** @dev See {IERC4626-maxRedeem}. */\n function maxRedeem(address owner) public view virtual returns (uint256) {\n return balanceOf(owner);\n }\n\n /** @dev See {IERC4626-previewDeposit}. */\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n return _convertToShares(assets, Math.Rounding.Floor);\n }\n\n /** @dev See {IERC4626-previewMint}. */\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n return _convertToAssets(shares, Math.Rounding.Ceil);\n }\n\n /** @dev See {IERC4626-previewWithdraw}. */\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n return _convertToShares(assets, Math.Rounding.Ceil);\n }\n\n /** @dev See {IERC4626-previewRedeem}. */\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n return _convertToAssets(shares, Math.Rounding.Floor);\n }\n\n /** @dev See {IERC4626-deposit}. */\n function deposit(uint256 assets, address receiver) public virtual returns (uint256) {\n uint256 maxAssets = maxDeposit(receiver);\n if (assets > maxAssets) {\n revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);\n }\n\n uint256 shares = previewDeposit(assets);\n _deposit(_msgSender(), receiver, assets, shares);\n\n return shares;\n }\n\n /** @dev See {IERC4626-mint}.\n *\n * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.\n * In this case, the shares will be minted without requiring any assets to be deposited.\n */\n function mint(uint256 shares, address receiver) public virtual returns (uint256) {\n uint256 maxShares = maxMint(receiver);\n if (shares > maxShares) {\n revert ERC4626ExceededMaxMint(receiver, shares, maxShares);\n }\n\n uint256 assets = previewMint(shares);\n _deposit(_msgSender(), receiver, assets, shares);\n\n return assets;\n }\n\n /** @dev See {IERC4626-withdraw}. */\n function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {\n uint256 maxAssets = maxWithdraw(owner);\n if (assets > maxAssets) {\n revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);\n }\n\n uint256 shares = previewWithdraw(assets);\n _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n return shares;\n }\n\n /** @dev See {IERC4626-redeem}. */\n function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {\n uint256 maxShares = maxRedeem(owner);\n if (shares > maxShares) {\n revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);\n }\n\n uint256 assets = previewRedeem(shares);\n _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n return assets;\n }\n\n /**\n * @dev Internal conversion function (from assets to shares) with support for rounding direction.\n */\n function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {\n return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);\n }\n\n /**\n * @dev Internal conversion function (from shares to assets) with support for rounding direction.\n */\n function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {\n return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);\n }\n\n /**\n * @dev Deposit/mint common workflow.\n */\n function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {\n // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the\n // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\n // calls the vault, which is assumed not malicious.\n //\n // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\n // assets are transferred and before the shares are minted, which is a valid state.\n // slither-disable-next-line reentrancy-no-eth\n SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);\n _mint(receiver, shares);\n\n emit Deposit(caller, receiver, assets, shares);\n }\n\n /**\n * @dev Withdraw/redeem common workflow.\n */\n function _withdraw(\n address caller,\n address receiver,\n address owner,\n uint256 assets,\n uint256 shares\n ) internal virtual {\n if (caller != owner) {\n _spendAllowance(owner, caller, shares);\n }\n\n // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\n // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\n // calls the vault, which is assumed not malicious.\n //\n // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\n // shares are burned and after the assets are transferred, which is a valid state.\n _burn(owner, shares);\n SafeERC20.safeTransfer(_asset, receiver, assets);\n\n emit Withdraw(caller, receiver, owner, assets, shares);\n }\n\n function _decimalsOffset() internal view virtual returns (uint8) {\n return 0;\n }\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n * doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n * token.safeTransferFrom(msg.sender, address(this), value);\n * ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n *\n * CAUTION: See Security Considerations above.\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/IERC20.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the value of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the value of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 value) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n * caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 value) external returns (bool);\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\n * allowance mechanism. `value` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC20Permit} from \"../extensions/IERC20Permit.sol\";\nimport {Address} from \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n /**\n * @dev An operation with an ERC20 token failed.\n */\n error SafeERC20FailedOperation(address token);\n\n /**\n * @dev Indicates a failed `decreaseAllowance` request.\n */\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n forceApprove(token, spender, oldAllowance + value);\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n * value, non-reverting calls are assumed to be successful.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n unchecked {\n uint256 currentAllowance = token.allowance(address(this), spender);\n if (currentAllowance < requestedDecrease) {\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n }\n forceApprove(token, spender, currentAllowance - requestedDecrease);\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n _callOptionalReturn(token, approvalCall);\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data);\n if (returndata.length != 0 && !abi.decode(returndata, (bool))) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n // and not revert is the subcall reverts.\n\n (bool success, bytes memory returndata) = address(token).call(data);\n return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;\n }\n}\n" - }, - "@openzeppelin/contracts/utils/Address.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error AddressInsufficientBalance(address account);\n\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedInnerCall();\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert AddressInsufficientBalance(address(this));\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert FailedInnerCall();\n }\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {FailedInnerCall} error.\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert AddressInsufficientBalance(address(this));\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n * unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {FailedInnerCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n */\n function _revert(bytes memory returndata) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert FailedInnerCall();\n }\n }\n}\n" - }, - "@openzeppelin/contracts/utils/Context.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n" - }, - "@openzeppelin/contracts/utils/math/Math.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Muldiv operation overflow.\n */\n error MathOverflowedMulDiv();\n\n enum Rounding {\n Floor, // Toward negative infinity\n Ceil, // Toward positive infinity\n Trunc, // Toward zero\n Expand // Away from zero\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds towards infinity instead\n * of rounding towards zero.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n if (b == 0) {\n // Guarantee the same behavior as in a regular Solidity division.\n return a / b;\n }\n\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n * denominator == 0.\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n * Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0 = x * y; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n if (denominator <= prod1) {\n revert MathOverflowedMulDiv();\n }\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n uint256 twos = denominator & (0 - denominator);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n // works in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n * towards zero.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n */\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n return uint8(rounding) % 2 == 1;\n }\n}\n" - }, - "@openzeppelin/contracts/utils/math/SafeCast.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeCast {\n /**\n * @dev Value doesn't fit in an uint of `bits` size.\n */\n error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n /**\n * @dev An int value doesn't fit in an uint of `bits` size.\n */\n error SafeCastOverflowedIntToUint(int256 value);\n\n /**\n * @dev Value doesn't fit in an int of `bits` size.\n */\n error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\n\n /**\n * @dev An uint value doesn't fit in an int of `bits` size.\n */\n error SafeCastOverflowedUintToInt(uint256 value);\n\n /**\n * @dev Returns the downcasted uint248 from uint256, reverting on\n * overflow (when the input is greater than largest uint248).\n *\n * Counterpart to Solidity's `uint248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n */\n function toUint248(uint256 value) internal pure returns (uint248) {\n if (value > type(uint248).max) {\n revert SafeCastOverflowedUintDowncast(248, value);\n }\n return uint248(value);\n }\n\n /**\n * @dev Returns the downcasted uint240 from uint256, reverting on\n * overflow (when the input is greater than largest uint240).\n *\n * Counterpart to Solidity's `uint240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n */\n function toUint240(uint256 value) internal pure returns (uint240) {\n if (value > type(uint240).max) {\n revert SafeCastOverflowedUintDowncast(240, value);\n }\n return uint240(value);\n }\n\n /**\n * @dev Returns the downcasted uint232 from uint256, reverting on\n * overflow (when the input is greater than largest uint232).\n *\n * Counterpart to Solidity's `uint232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n */\n function toUint232(uint256 value) internal pure returns (uint232) {\n if (value > type(uint232).max) {\n revert SafeCastOverflowedUintDowncast(232, value);\n }\n return uint232(value);\n }\n\n /**\n * @dev Returns the downcasted uint224 from uint256, reverting on\n * overflow (when the input is greater than largest uint224).\n *\n * Counterpart to Solidity's `uint224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n if (value > type(uint224).max) {\n revert SafeCastOverflowedUintDowncast(224, value);\n }\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint216 from uint256, reverting on\n * overflow (when the input is greater than largest uint216).\n *\n * Counterpart to Solidity's `uint216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n */\n function toUint216(uint256 value) internal pure returns (uint216) {\n if (value > type(uint216).max) {\n revert SafeCastOverflowedUintDowncast(216, value);\n }\n return uint216(value);\n }\n\n /**\n * @dev Returns the downcasted uint208 from uint256, reverting on\n * overflow (when the input is greater than largest uint208).\n *\n * Counterpart to Solidity's `uint208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n */\n function toUint208(uint256 value) internal pure returns (uint208) {\n if (value > type(uint208).max) {\n revert SafeCastOverflowedUintDowncast(208, value);\n }\n return uint208(value);\n }\n\n /**\n * @dev Returns the downcasted uint200 from uint256, reverting on\n * overflow (when the input is greater than largest uint200).\n *\n * Counterpart to Solidity's `uint200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n */\n function toUint200(uint256 value) internal pure returns (uint200) {\n if (value > type(uint200).max) {\n revert SafeCastOverflowedUintDowncast(200, value);\n }\n return uint200(value);\n }\n\n /**\n * @dev Returns the downcasted uint192 from uint256, reverting on\n * overflow (when the input is greater than largest uint192).\n *\n * Counterpart to Solidity's `uint192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n */\n function toUint192(uint256 value) internal pure returns (uint192) {\n if (value > type(uint192).max) {\n revert SafeCastOverflowedUintDowncast(192, value);\n }\n return uint192(value);\n }\n\n /**\n * @dev Returns the downcasted uint184 from uint256, reverting on\n * overflow (when the input is greater than largest uint184).\n *\n * Counterpart to Solidity's `uint184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n */\n function toUint184(uint256 value) internal pure returns (uint184) {\n if (value > type(uint184).max) {\n revert SafeCastOverflowedUintDowncast(184, value);\n }\n return uint184(value);\n }\n\n /**\n * @dev Returns the downcasted uint176 from uint256, reverting on\n * overflow (when the input is greater than largest uint176).\n *\n * Counterpart to Solidity's `uint176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n */\n function toUint176(uint256 value) internal pure returns (uint176) {\n if (value > type(uint176).max) {\n revert SafeCastOverflowedUintDowncast(176, value);\n }\n return uint176(value);\n }\n\n /**\n * @dev Returns the downcasted uint168 from uint256, reverting on\n * overflow (when the input is greater than largest uint168).\n *\n * Counterpart to Solidity's `uint168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n */\n function toUint168(uint256 value) internal pure returns (uint168) {\n if (value > type(uint168).max) {\n revert SafeCastOverflowedUintDowncast(168, value);\n }\n return uint168(value);\n }\n\n /**\n * @dev Returns the downcasted uint160 from uint256, reverting on\n * overflow (when the input is greater than largest uint160).\n *\n * Counterpart to Solidity's `uint160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n */\n function toUint160(uint256 value) internal pure returns (uint160) {\n if (value > type(uint160).max) {\n revert SafeCastOverflowedUintDowncast(160, value);\n }\n return uint160(value);\n }\n\n /**\n * @dev Returns the downcasted uint152 from uint256, reverting on\n * overflow (when the input is greater than largest uint152).\n *\n * Counterpart to Solidity's `uint152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n */\n function toUint152(uint256 value) internal pure returns (uint152) {\n if (value > type(uint152).max) {\n revert SafeCastOverflowedUintDowncast(152, value);\n }\n return uint152(value);\n }\n\n /**\n * @dev Returns the downcasted uint144 from uint256, reverting on\n * overflow (when the input is greater than largest uint144).\n *\n * Counterpart to Solidity's `uint144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n */\n function toUint144(uint256 value) internal pure returns (uint144) {\n if (value > type(uint144).max) {\n revert SafeCastOverflowedUintDowncast(144, value);\n }\n return uint144(value);\n }\n\n /**\n * @dev Returns the downcasted uint136 from uint256, reverting on\n * overflow (when the input is greater than largest uint136).\n *\n * Counterpart to Solidity's `uint136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n */\n function toUint136(uint256 value) internal pure returns (uint136) {\n if (value > type(uint136).max) {\n revert SafeCastOverflowedUintDowncast(136, value);\n }\n return uint136(value);\n }\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n if (value > type(uint128).max) {\n revert SafeCastOverflowedUintDowncast(128, value);\n }\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint120 from uint256, reverting on\n * overflow (when the input is greater than largest uint120).\n *\n * Counterpart to Solidity's `uint120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n */\n function toUint120(uint256 value) internal pure returns (uint120) {\n if (value > type(uint120).max) {\n revert SafeCastOverflowedUintDowncast(120, value);\n }\n return uint120(value);\n }\n\n /**\n * @dev Returns the downcasted uint112 from uint256, reverting on\n * overflow (when the input is greater than largest uint112).\n *\n * Counterpart to Solidity's `uint112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n */\n function toUint112(uint256 value) internal pure returns (uint112) {\n if (value > type(uint112).max) {\n revert SafeCastOverflowedUintDowncast(112, value);\n }\n return uint112(value);\n }\n\n /**\n * @dev Returns the downcasted uint104 from uint256, reverting on\n * overflow (when the input is greater than largest uint104).\n *\n * Counterpart to Solidity's `uint104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n */\n function toUint104(uint256 value) internal pure returns (uint104) {\n if (value > type(uint104).max) {\n revert SafeCastOverflowedUintDowncast(104, value);\n }\n return uint104(value);\n }\n\n /**\n * @dev Returns the downcasted uint96 from uint256, reverting on\n * overflow (when the input is greater than largest uint96).\n *\n * Counterpart to Solidity's `uint96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n if (value > type(uint96).max) {\n revert SafeCastOverflowedUintDowncast(96, value);\n }\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint88 from uint256, reverting on\n * overflow (when the input is greater than largest uint88).\n *\n * Counterpart to Solidity's `uint88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n */\n function toUint88(uint256 value) internal pure returns (uint88) {\n if (value > type(uint88).max) {\n revert SafeCastOverflowedUintDowncast(88, value);\n }\n return uint88(value);\n }\n\n /**\n * @dev Returns the downcasted uint80 from uint256, reverting on\n * overflow (when the input is greater than largest uint80).\n *\n * Counterpart to Solidity's `uint80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n */\n function toUint80(uint256 value) internal pure returns (uint80) {\n if (value > type(uint80).max) {\n revert SafeCastOverflowedUintDowncast(80, value);\n }\n return uint80(value);\n }\n\n /**\n * @dev Returns the downcasted uint72 from uint256, reverting on\n * overflow (when the input is greater than largest uint72).\n *\n * Counterpart to Solidity's `uint72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n */\n function toUint72(uint256 value) internal pure returns (uint72) {\n if (value > type(uint72).max) {\n revert SafeCastOverflowedUintDowncast(72, value);\n }\n return uint72(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n if (value > type(uint64).max) {\n revert SafeCastOverflowedUintDowncast(64, value);\n }\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint56 from uint256, reverting on\n * overflow (when the input is greater than largest uint56).\n *\n * Counterpart to Solidity's `uint56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n */\n function toUint56(uint256 value) internal pure returns (uint56) {\n if (value > type(uint56).max) {\n revert SafeCastOverflowedUintDowncast(56, value);\n }\n return uint56(value);\n }\n\n /**\n * @dev Returns the downcasted uint48 from uint256, reverting on\n * overflow (when the input is greater than largest uint48).\n *\n * Counterpart to Solidity's `uint48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n */\n function toUint48(uint256 value) internal pure returns (uint48) {\n if (value > type(uint48).max) {\n revert SafeCastOverflowedUintDowncast(48, value);\n }\n return uint48(value);\n }\n\n /**\n * @dev Returns the downcasted uint40 from uint256, reverting on\n * overflow (when the input is greater than largest uint40).\n *\n * Counterpart to Solidity's `uint40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n */\n function toUint40(uint256 value) internal pure returns (uint40) {\n if (value > type(uint40).max) {\n revert SafeCastOverflowedUintDowncast(40, value);\n }\n return uint40(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n if (value > type(uint32).max) {\n revert SafeCastOverflowedUintDowncast(32, value);\n }\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint24 from uint256, reverting on\n * overflow (when the input is greater than largest uint24).\n *\n * Counterpart to Solidity's `uint24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n */\n function toUint24(uint256 value) internal pure returns (uint24) {\n if (value > type(uint24).max) {\n revert SafeCastOverflowedUintDowncast(24, value);\n }\n return uint24(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n if (value > type(uint16).max) {\n revert SafeCastOverflowedUintDowncast(16, value);\n }\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n if (value > type(uint8).max) {\n revert SafeCastOverflowedUintDowncast(8, value);\n }\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n if (value < 0) {\n revert SafeCastOverflowedIntToUint(value);\n }\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int248 from int256, reverting on\n * overflow (when the input is less than smallest int248 or\n * greater than largest int248).\n *\n * Counterpart to Solidity's `int248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n */\n function toInt248(int256 value) internal pure returns (int248 downcasted) {\n downcasted = int248(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(248, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int240 from int256, reverting on\n * overflow (when the input is less than smallest int240 or\n * greater than largest int240).\n *\n * Counterpart to Solidity's `int240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n */\n function toInt240(int256 value) internal pure returns (int240 downcasted) {\n downcasted = int240(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(240, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int232 from int256, reverting on\n * overflow (when the input is less than smallest int232 or\n * greater than largest int232).\n *\n * Counterpart to Solidity's `int232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n */\n function toInt232(int256 value) internal pure returns (int232 downcasted) {\n downcasted = int232(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(232, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int224 from int256, reverting on\n * overflow (when the input is less than smallest int224 or\n * greater than largest int224).\n *\n * Counterpart to Solidity's `int224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n */\n function toInt224(int256 value) internal pure returns (int224 downcasted) {\n downcasted = int224(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(224, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int216 from int256, reverting on\n * overflow (when the input is less than smallest int216 or\n * greater than largest int216).\n *\n * Counterpart to Solidity's `int216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n */\n function toInt216(int256 value) internal pure returns (int216 downcasted) {\n downcasted = int216(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(216, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int208 from int256, reverting on\n * overflow (when the input is less than smallest int208 or\n * greater than largest int208).\n *\n * Counterpart to Solidity's `int208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n */\n function toInt208(int256 value) internal pure returns (int208 downcasted) {\n downcasted = int208(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(208, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int200 from int256, reverting on\n * overflow (when the input is less than smallest int200 or\n * greater than largest int200).\n *\n * Counterpart to Solidity's `int200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n */\n function toInt200(int256 value) internal pure returns (int200 downcasted) {\n downcasted = int200(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(200, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int192 from int256, reverting on\n * overflow (when the input is less than smallest int192 or\n * greater than largest int192).\n *\n * Counterpart to Solidity's `int192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n */\n function toInt192(int256 value) internal pure returns (int192 downcasted) {\n downcasted = int192(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(192, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int184 from int256, reverting on\n * overflow (when the input is less than smallest int184 or\n * greater than largest int184).\n *\n * Counterpart to Solidity's `int184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n */\n function toInt184(int256 value) internal pure returns (int184 downcasted) {\n downcasted = int184(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(184, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int176 from int256, reverting on\n * overflow (when the input is less than smallest int176 or\n * greater than largest int176).\n *\n * Counterpart to Solidity's `int176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n */\n function toInt176(int256 value) internal pure returns (int176 downcasted) {\n downcasted = int176(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(176, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int168 from int256, reverting on\n * overflow (when the input is less than smallest int168 or\n * greater than largest int168).\n *\n * Counterpart to Solidity's `int168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n */\n function toInt168(int256 value) internal pure returns (int168 downcasted) {\n downcasted = int168(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(168, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int160 from int256, reverting on\n * overflow (when the input is less than smallest int160 or\n * greater than largest int160).\n *\n * Counterpart to Solidity's `int160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n */\n function toInt160(int256 value) internal pure returns (int160 downcasted) {\n downcasted = int160(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(160, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int152 from int256, reverting on\n * overflow (when the input is less than smallest int152 or\n * greater than largest int152).\n *\n * Counterpart to Solidity's `int152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n */\n function toInt152(int256 value) internal pure returns (int152 downcasted) {\n downcasted = int152(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(152, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int144 from int256, reverting on\n * overflow (when the input is less than smallest int144 or\n * greater than largest int144).\n *\n * Counterpart to Solidity's `int144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n */\n function toInt144(int256 value) internal pure returns (int144 downcasted) {\n downcasted = int144(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(144, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int136 from int256, reverting on\n * overflow (when the input is less than smallest int136 or\n * greater than largest int136).\n *\n * Counterpart to Solidity's `int136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n */\n function toInt136(int256 value) internal pure returns (int136 downcasted) {\n downcasted = int136(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(136, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n */\n function toInt128(int256 value) internal pure returns (int128 downcasted) {\n downcasted = int128(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(128, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int120 from int256, reverting on\n * overflow (when the input is less than smallest int120 or\n * greater than largest int120).\n *\n * Counterpart to Solidity's `int120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n */\n function toInt120(int256 value) internal pure returns (int120 downcasted) {\n downcasted = int120(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(120, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int112 from int256, reverting on\n * overflow (when the input is less than smallest int112 or\n * greater than largest int112).\n *\n * Counterpart to Solidity's `int112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n */\n function toInt112(int256 value) internal pure returns (int112 downcasted) {\n downcasted = int112(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(112, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int104 from int256, reverting on\n * overflow (when the input is less than smallest int104 or\n * greater than largest int104).\n *\n * Counterpart to Solidity's `int104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n */\n function toInt104(int256 value) internal pure returns (int104 downcasted) {\n downcasted = int104(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(104, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int96 from int256, reverting on\n * overflow (when the input is less than smallest int96 or\n * greater than largest int96).\n *\n * Counterpart to Solidity's `int96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n */\n function toInt96(int256 value) internal pure returns (int96 downcasted) {\n downcasted = int96(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(96, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int88 from int256, reverting on\n * overflow (when the input is less than smallest int88 or\n * greater than largest int88).\n *\n * Counterpart to Solidity's `int88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n */\n function toInt88(int256 value) internal pure returns (int88 downcasted) {\n downcasted = int88(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(88, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int80 from int256, reverting on\n * overflow (when the input is less than smallest int80 or\n * greater than largest int80).\n *\n * Counterpart to Solidity's `int80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n */\n function toInt80(int256 value) internal pure returns (int80 downcasted) {\n downcasted = int80(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(80, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int72 from int256, reverting on\n * overflow (when the input is less than smallest int72 or\n * greater than largest int72).\n *\n * Counterpart to Solidity's `int72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n */\n function toInt72(int256 value) internal pure returns (int72 downcasted) {\n downcasted = int72(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(72, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n */\n function toInt64(int256 value) internal pure returns (int64 downcasted) {\n downcasted = int64(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(64, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int56 from int256, reverting on\n * overflow (when the input is less than smallest int56 or\n * greater than largest int56).\n *\n * Counterpart to Solidity's `int56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n */\n function toInt56(int256 value) internal pure returns (int56 downcasted) {\n downcasted = int56(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(56, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int48 from int256, reverting on\n * overflow (when the input is less than smallest int48 or\n * greater than largest int48).\n *\n * Counterpart to Solidity's `int48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n */\n function toInt48(int256 value) internal pure returns (int48 downcasted) {\n downcasted = int48(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(48, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int40 from int256, reverting on\n * overflow (when the input is less than smallest int40 or\n * greater than largest int40).\n *\n * Counterpart to Solidity's `int40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n */\n function toInt40(int256 value) internal pure returns (int40 downcasted) {\n downcasted = int40(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(40, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n */\n function toInt32(int256 value) internal pure returns (int32 downcasted) {\n downcasted = int32(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(32, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int24 from int256, reverting on\n * overflow (when the input is less than smallest int24 or\n * greater than largest int24).\n *\n * Counterpart to Solidity's `int24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n */\n function toInt24(int256 value) internal pure returns (int24 downcasted) {\n downcasted = int24(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(24, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n */\n function toInt16(int256 value) internal pure returns (int16 downcasted) {\n downcasted = int16(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(16, value);\n }\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n */\n function toInt8(int256 value) internal pure returns (int8 downcasted) {\n downcasted = int8(value);\n if (downcasted != value) {\n revert SafeCastOverflowedIntDowncast(8, value);\n }\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n if (value > uint256(type(int256).max)) {\n revert SafeCastOverflowedUintToInt(value);\n }\n return int256(value);\n }\n}\n" - }, - "contracts/AcreBitcoinDepositor.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport \"@openzeppelin/contracts/access/Ownable2Step.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeCast} from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport \"@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol\";\n\nimport {stBTC} from \"./stBTC.sol\";\n\n// TODO: Make Upgradable\n// TODO: Make Pausable\n\n/// @title Acre Bitcoin Depositor contract.\n/// @notice The contract integrates Acre staking with tBTC minting.\n/// User who wants to stake BTC in Acre should submit a Bitcoin transaction\n/// to the most recently created off-chain ECDSA wallets of the tBTC Bridge\n/// using pay-to-script-hash (P2SH) or pay-to-witness-script-hash (P2WSH)\n/// containing hashed information about this Depositor contract address,\n/// and staker's Ethereum address.\n/// Then, the staker initiates tBTC minting by revealing their Ethereum\n/// address along with their deposit blinding factor, refund public key\n/// hash and refund locktime on the tBTC Bridge through this Depositor\n/// contract.\n/// The off-chain ECDSA wallet and Optimistic Minting bots listen for these\n/// sorts of messages and when they get one, they check the Bitcoin network\n/// to make sure the deposit lines up. Majority of tBTC minting is finalized\n/// by the Optimistic Minting process, where Minter bot initializes\n/// minting process and if there is no veto from the Guardians, the\n/// process is finalized and tBTC minted to the Depositor address. If\n/// the revealed deposit is not handled by the Optimistic Minting process\n/// the off-chain ECDSA wallet may decide to pick the deposit transaction\n/// for sweeping, and when the sweep operation is confirmed on the Bitcoin\n/// network, the tBTC Bridge and tBTC vault mint the tBTC token to the\n/// Depositor address. After tBTC is minted to the Depositor, on the stake\n/// finalization tBTC is staked in stBTC contract and stBTC shares are emitted\n/// to the staker.\ncontract AcreBitcoinDepositor is AbstractTBTCDepositor, Ownable2Step {\n using SafeERC20 for IERC20;\n\n /// @notice State of the stake request.\n enum StakeRequestState {\n Unknown,\n Initialized,\n Finalized,\n Queued,\n FinalizedFromQueue,\n CancelledFromQueue\n }\n\n struct StakeRequest {\n // State of the stake request.\n StakeRequestState state;\n // The address to which the stBTC shares will be minted. Stored only when\n // request is queued.\n address staker;\n // tBTC token amount to stake after deducting tBTC minting fees and the\n // Depositor fee. Stored only when request is queued.\n uint88 queuedAmount;\n }\n\n /// @notice Mapping of stake requests.\n /// @dev The key is a deposit key identifying the deposit.\n mapping(uint256 => StakeRequest) public stakeRequests;\n\n /// @notice tBTC Token contract.\n // TODO: Remove slither disable when introducing upgradeability.\n // slither-disable-next-line immutable-states\n IERC20 public tbtcToken;\n\n /// @notice stBTC contract.\n // TODO: Remove slither disable when introducing upgradeability.\n // slither-disable-next-line immutable-states\n stBTC public stbtc;\n\n /// @notice Divisor used to compute the depositor fee taken from each deposit\n /// and transferred to the treasury upon stake request finalization.\n /// @dev That fee is computed as follows:\n /// `depositorFee = depositedAmount / depositorFeeDivisor`\n /// for example, if the depositor fee needs to be 2% of each deposit,\n /// the `depositorFeeDivisor` should be set to `50` because\n /// `1/50 = 0.02 = 2%`.\n uint64 public depositorFeeDivisor;\n\n /// @notice Emitted when a stake request is initialized.\n /// @dev Deposit details can be fetched from {{ Bridge.DepositRevealed }}\n /// event emitted in the same transaction.\n /// @param depositKey Deposit key identifying the deposit.\n /// @param caller Address that initialized the stake request.\n /// @param staker The address to which the stBTC shares will be minted.\n event StakeRequestInitialized(\n uint256 indexed depositKey,\n address indexed caller,\n address indexed staker\n );\n\n /// @notice Emitted when bridging completion has been notified.\n /// @param depositKey Deposit key identifying the deposit.\n /// @param caller Address that notified about bridging completion.\n /// @param referral Identifier of a partner in the referral program.\n /// @param bridgedAmount Amount of tBTC tokens that was bridged by the tBTC bridge.\n /// @param depositorFee Depositor fee amount.\n event BridgingCompleted(\n uint256 indexed depositKey,\n address indexed caller,\n uint16 indexed referral,\n uint256 bridgedAmount,\n uint256 depositorFee\n );\n\n /// @notice Emitted when a stake request is finalized.\n /// @dev Deposit details can be fetched from {{ ERC4626.Deposit }}\n /// event emitted in the same transaction.\n /// @param depositKey Deposit key identifying the deposit.\n /// @param caller Address that finalized the stake request.\n /// @param stakedAmount Amount of staked tBTC tokens.\n event StakeRequestFinalized(\n uint256 indexed depositKey,\n address indexed caller,\n uint256 stakedAmount\n );\n\n /// @notice Emitted when a stake request is queued.\n /// @param depositKey Deposit key identifying the deposit.\n /// @param caller Address that finalized the stake request.\n /// @param queuedAmount Amount of queued tBTC tokens.\n event StakeRequestQueued(\n uint256 indexed depositKey,\n address indexed caller,\n uint256 queuedAmount\n );\n\n /// @notice Emitted when a stake request is finalized from the queue.\n /// @dev Deposit details can be fetched from {{ ERC4626.Deposit }}\n /// event emitted in the same transaction.\n /// @param depositKey Deposit key identifying the deposit.\n /// @param caller Address that finalized the stake request.\n /// @param stakedAmount Amount of staked tBTC tokens.\n event StakeRequestFinalizedFromQueue(\n uint256 indexed depositKey,\n address indexed caller,\n uint256 stakedAmount\n );\n\n /// @notice Emitted when a queued stake request is cancelled.\n /// @param depositKey Deposit key identifying the deposit.\n /// @param staker Address of the staker.\n /// @param amountToStake Amount of queued tBTC tokens that got cancelled.\n event StakeRequestCancelledFromQueue(\n uint256 indexed depositKey,\n address indexed staker,\n uint256 amountToStake\n );\n\n /// @notice Emitted when a depositor fee divisor is updated.\n /// @param depositorFeeDivisor New value of the depositor fee divisor.\n event DepositorFeeDivisorUpdated(uint64 depositorFeeDivisor);\n\n /// Reverts if the tBTC Token address is zero.\n error TbtcTokenZeroAddress();\n\n /// Reverts if the stBTC address is zero.\n error StbtcZeroAddress();\n\n /// @dev Staker address is zero.\n error StakerIsZeroAddress();\n\n /// @dev Attempted to execute function for stake request in unexpected current\n /// state.\n error UnexpectedStakeRequestState(\n StakeRequestState currentState,\n StakeRequestState expectedState\n );\n\n /// @dev Attempted to finalize bridging with depositor's contract tBTC balance\n /// lower than the calculated bridged tBTC amount. This error means\n /// that Governance should top-up the tBTC reserve for bridging fees\n /// approximation.\n error InsufficientTbtcBalance(\n uint256 amountToStake,\n uint256 currentBalance\n );\n\n /// @dev Attempted to notify a bridging completion, while it was already\n /// notified.\n error BridgingCompletionAlreadyNotified();\n\n /// @dev Attempted to finalize a stake request, while bridging completion has\n /// not been notified yet.\n error BridgingNotCompleted();\n\n /// @dev Calculated depositor fee exceeds the amount of minted tBTC tokens.\n error DepositorFeeExceedsBridgedAmount(\n uint256 depositorFee,\n uint256 bridgedAmount\n );\n\n /// @dev Attempted to call bridging finalization for a stake request for\n /// which the function was already called.\n error BridgingFinalizationAlreadyCalled();\n\n /// @dev Attempted to finalize or cancel a stake request that was not added\n /// to the queue, or was already finalized or cancelled.\n error StakeRequestNotQueued();\n\n /// @dev Attempted to call function by an account that is not the staker.\n error CallerNotStaker();\n\n /// @notice Acre Bitcoin Depositor contract constructor.\n /// @param bridge tBTC Bridge contract instance.\n /// @param tbtcVault tBTC Vault contract instance.\n /// @param _tbtcToken tBTC token contract instance.\n /// @param _stbtc stBTC contract instance.\n // TODO: Move to initializer when making the contract upgradeable.\n constructor(\n address bridge,\n address tbtcVault,\n address _tbtcToken,\n address _stbtc\n ) Ownable(msg.sender) {\n __AbstractTBTCDepositor_initialize(bridge, tbtcVault);\n\n if (address(_tbtcToken) == address(0)) {\n revert TbtcTokenZeroAddress();\n }\n if (address(_stbtc) == address(0)) {\n revert StbtcZeroAddress();\n }\n\n tbtcToken = IERC20(_tbtcToken);\n stbtc = stBTC(_stbtc);\n\n depositorFeeDivisor = 1000; // 1/1000 == 10bps == 0.1% == 0.001\n }\n\n /// @notice This function allows staking process initialization for a Bitcoin\n /// deposit made by an user with a P2(W)SH transaction. It uses the\n /// supplied information to reveal a deposit to the tBTC Bridge contract.\n /// @dev Requirements:\n /// - The revealed vault address must match the TBTCVault address,\n /// - All requirements from {Bridge#revealDepositWithExtraData}\n /// function must be met.\n /// - `staker` must be the staker address used in the P2(W)SH BTC\n /// deposit transaction as part of the extra data.\n /// - `referral` must be the referral info used in the P2(W)SH BTC\n /// deposit transaction as part of the extra data.\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n /// @param fundingTx Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.\n /// @param reveal Deposit reveal data, see `IBridgeTypes.DepositRevealInfo`.\n /// @param staker The address to which the stBTC shares will be minted.\n /// @param referral Data used for referral program.\n function initializeStake(\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n IBridgeTypes.DepositRevealInfo calldata reveal,\n address staker,\n uint16 referral\n ) external {\n if (staker == address(0)) revert StakerIsZeroAddress();\n\n // We don't check if the request was already initialized, as this check\n // is enforced in `_initializeDeposit` when calling the\n // `Bridge.revealDepositWithExtraData` function.\n uint256 depositKey = _initializeDeposit(\n fundingTx,\n reveal,\n encodeExtraData(staker, referral)\n );\n\n transitionStakeRequestState(\n depositKey,\n StakeRequestState.Unknown,\n StakeRequestState.Initialized\n );\n\n emit StakeRequestInitialized(depositKey, msg.sender, staker);\n }\n\n /// @notice This function should be called for previously initialized stake\n /// request, after tBTC bridging process was finalized.\n /// It stakes the tBTC from the given deposit into stBTC, emitting the\n /// stBTC shares to the staker specified in the deposit extra data\n /// and using the referral provided in the extra data.\n /// @dev In case depositing in stBTC vault fails (e.g. because of the\n /// maximum deposit limit being reached), the `queueStake` function\n /// should be called to add the stake request to the staking queue.\n /// @param depositKey Deposit key identifying the deposit.\n function finalizeStake(uint256 depositKey) external {\n transitionStakeRequestState(\n depositKey,\n StakeRequestState.Initialized,\n StakeRequestState.Finalized\n );\n\n (uint256 amountToStake, address staker) = finalizeBridging(depositKey);\n\n emit StakeRequestFinalized(depositKey, msg.sender, amountToStake);\n\n // Deposit tBTC in stBTC.\n tbtcToken.safeIncreaseAllowance(address(stbtc), amountToStake);\n // slither-disable-next-line unused-return\n stbtc.deposit(amountToStake, staker);\n }\n\n /// @notice This function should be called for previously initialized stake\n /// request, after tBTC bridging process was finalized, in case the\n /// `finalizeStake` failed due to stBTC vault deposit limit\n /// being reached.\n /// @dev It queues the stake request, until the stBTC vault is ready to\n /// accept the deposit. The request must be finalized with `finalizeQueuedStake`\n /// after the limit is increased or other user withdraws their funds\n /// from the stBTC contract to make place for another deposit.\n /// The staker has a possibility to submit `cancelQueuedStake` that\n /// will withdraw the minted tBTC token and abort staking process.\n /// @param depositKey Deposit key identifying the deposit.\n function queueStake(uint256 depositKey) external {\n transitionStakeRequestState(\n depositKey,\n StakeRequestState.Initialized,\n StakeRequestState.Queued\n );\n\n StakeRequest storage request = stakeRequests[depositKey];\n\n uint256 amountToStake;\n (amountToStake, request.staker) = finalizeBridging(depositKey);\n\n request.queuedAmount = SafeCast.toUint88(amountToStake);\n\n emit StakeRequestQueued(depositKey, msg.sender, request.queuedAmount);\n }\n\n /// @notice This function should be called for previously queued stake\n /// request, when stBTC vault is able to accept a deposit.\n /// @param depositKey Deposit key identifying the deposit.\n function finalizeQueuedStake(uint256 depositKey) external {\n transitionStakeRequestState(\n depositKey,\n StakeRequestState.Queued,\n StakeRequestState.FinalizedFromQueue\n );\n\n StakeRequest storage request = stakeRequests[depositKey];\n\n if (request.queuedAmount == 0) revert StakeRequestNotQueued();\n\n uint256 amountToStake = request.queuedAmount;\n delete (request.queuedAmount);\n\n emit StakeRequestFinalizedFromQueue(\n depositKey,\n msg.sender,\n amountToStake\n );\n\n // Deposit tBTC in stBTC.\n tbtcToken.safeIncreaseAllowance(address(stbtc), amountToStake);\n // slither-disable-next-line unused-return\n stbtc.deposit(amountToStake, request.staker);\n }\n\n /// @notice Cancel queued stake.\n /// The function can be called by the staker to recover tBTC that cannot\n /// be finalized to stake in stBTC contract due to a deposit limit being\n /// reached.\n /// @dev This function can be called only after the stake request was added\n /// to queue.\n /// @dev Only staker provided in the extra data of the stake request can\n /// call this function.\n /// @param depositKey Deposit key identifying the deposit.\n function cancelQueuedStake(uint256 depositKey) external {\n transitionStakeRequestState(\n depositKey,\n StakeRequestState.Queued,\n StakeRequestState.CancelledFromQueue\n );\n\n StakeRequest storage request = stakeRequests[depositKey];\n\n if (request.queuedAmount == 0) revert StakeRequestNotQueued();\n\n // Check if caller is the staker.\n if (msg.sender != request.staker) revert CallerNotStaker();\n\n uint256 amount = request.queuedAmount;\n delete (request.queuedAmount);\n\n emit StakeRequestCancelledFromQueue(depositKey, request.staker, amount);\n\n tbtcToken.safeTransfer(request.staker, amount);\n }\n\n /// @notice Updates the depositor fee divisor.\n /// @param newDepositorFeeDivisor New depositor fee divisor value.\n function updateDepositorFeeDivisor(\n uint64 newDepositorFeeDivisor\n ) external onlyOwner {\n // TODO: Introduce a parameters update process.\n depositorFeeDivisor = newDepositorFeeDivisor;\n\n emit DepositorFeeDivisorUpdated(newDepositorFeeDivisor);\n }\n\n // TODO: Handle minimum deposit amount in tBTC Bridge vs stBTC.\n\n /// @notice Encodes staker address and referral as extra data.\n /// @dev Packs the data to bytes32: 20 bytes of staker address and\n /// 2 bytes of referral, 10 bytes of trailing zeros.\n /// @param staker The address to which the stBTC shares will be minted.\n /// @param referral Data used for referral program.\n /// @return Encoded extra data.\n function encodeExtraData(\n address staker,\n uint16 referral\n ) public pure returns (bytes32) {\n return bytes32(abi.encodePacked(staker, referral));\n }\n\n /// @notice Decodes staker address and referral from extra data.\n /// @dev Unpacks the data from bytes32: 20 bytes of staker address and\n /// 2 bytes of referral, 10 bytes of trailing zeros.\n /// @param extraData Encoded extra data.\n /// @return staker The address to which the stBTC shares will be minted.\n /// @return referral Data used for referral program.\n function decodeExtraData(\n bytes32 extraData\n ) public pure returns (address staker, uint16 referral) {\n // First 20 bytes of extra data is staker address.\n staker = address(uint160(bytes20(extraData)));\n // Next 2 bytes of extra data is referral info.\n referral = uint16(bytes2(extraData << (8 * 20)));\n }\n\n /// @notice This function is used for state transitions. It ensures the current\n /// stakte matches expected, and updates the stake request to a new\n /// state.\n /// @param depositKey Deposit key identifying the deposit.\n /// @param expectedState Expected current stake request state.\n /// @param newState New stake request state.\n function transitionStakeRequestState(\n uint256 depositKey,\n StakeRequestState expectedState,\n StakeRequestState newState\n ) internal {\n // Validate current stake request state.\n if (stakeRequests[depositKey].state != expectedState)\n revert UnexpectedStakeRequestState(\n stakeRequests[depositKey].state,\n expectedState\n );\n\n // Transition to a new state.\n stakeRequests[depositKey].state = newState;\n }\n\n /// @notice This function should be called for previously initialized stake\n /// request, after tBTC minting process completed, meaning tBTC was\n /// minted to this contract.\n /// @dev It calculates the amount to stake based on the approximate minted\n /// tBTC amount reduced by the depositor fee.\n /// @dev IMPORTANT NOTE: The minted tBTC amount used by this function is an\n /// approximation. See documentation of the\n /// {{AbstractTBTCDepositor#_calculateTbtcAmount}} responsible for calculating\n /// this value for more details.\n /// @dev In case balance of tBTC tokens in this contract doesn't meet the\n /// calculated tBTC amount, the function reverts with `InsufficientTbtcBalance`\n /// error. This case requires Governance's validation, as tBTC Bridge minting\n /// fees might changed in the way that reserve mentioned in\n /// {{AbstractTBTCDepositor#_calculateTbtcAmount}} needs a top-up.\n /// @param depositKey Deposit key identifying the deposit.\n /// @return amountToStake tBTC token amount to stake after deducting tBTC bridging\n /// fees and the depositor fee.\n /// @return staker The address to which the stBTC shares will be minted.\n function finalizeBridging(\n uint256 depositKey\n ) internal returns (uint256, address) {\n (\n uint256 initialDepositAmount,\n uint256 tbtcAmount,\n bytes32 extraData\n ) = _finalizeDeposit(depositKey);\n\n // Check if current balance is sufficient to finalize bridging of `tbtcAmount`.\n uint256 currentBalance = tbtcToken.balanceOf(address(this));\n if (tbtcAmount > tbtcToken.balanceOf(address(this))) {\n revert InsufficientTbtcBalance(tbtcAmount, currentBalance);\n }\n\n // Compute depositor fee. The fee is calculated based on the initial funding\n // transaction amount, before the tBTC protocol network fees were taken.\n uint256 depositorFee = depositorFeeDivisor > 0\n ? (initialDepositAmount / depositorFeeDivisor)\n : 0;\n\n // Ensure the depositor fee does not exceed the approximate minted tBTC\n // amount.\n if (depositorFee >= tbtcAmount) {\n revert DepositorFeeExceedsBridgedAmount(depositorFee, tbtcAmount);\n }\n\n uint256 amountToStake = tbtcAmount - depositorFee;\n\n (address staker, uint16 referral) = decodeExtraData(extraData);\n\n // Emit event for accounting purposes to track partner's referral ID and\n // depositor fee taken.\n emit BridgingCompleted(\n depositKey,\n msg.sender,\n referral,\n tbtcAmount,\n depositorFee\n );\n\n // Transfer depositor fee to the treasury wallet.\n if (depositorFee > 0) {\n tbtcToken.safeTransfer(stbtc.treasury(), depositorFee);\n }\n\n return (amountToStake, staker);\n }\n}\n" - }, - "contracts/Dispatcher.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport \"@openzeppelin/contracts/access/Ownable2Step.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\nimport \"./Router.sol\";\nimport \"./stBTC.sol\";\n\n/// @title Dispatcher\n/// @notice Dispatcher is a contract that routes tBTC from stBTC to\n/// yield vaults and back. Vaults supply yield strategies with tBTC that\n/// generate yield for Bitcoin holders.\ncontract Dispatcher is Router, Ownable2Step {\n using SafeERC20 for IERC20;\n\n /// Struct holds information about a vault.\n struct VaultInfo {\n bool authorized;\n }\n\n /// The main stBTC contract holding tBTC deposited by stakers.\n stBTC public immutable stbtc;\n /// tBTC token contract.\n IERC20 public immutable tbtc;\n /// Address of the maintainer bot.\n address public maintainer;\n\n /// Authorized Yield Vaults that implement ERC4626 standard. These\n /// vaults deposit assets to yield strategies, e.g. Uniswap V3\n /// WBTC/TBTC pool. Vault can be a part of Acre ecosystem or can be\n /// implemented externally. As long as it complies with ERC4626\n /// standard and is authorized by the owner it can be plugged into\n /// Acre.\n address[] public vaults;\n /// Mapping of vaults to their information.\n mapping(address => VaultInfo) public vaultsInfo;\n\n /// Emitted when a vault is authorized.\n /// @param vault Address of the vault.\n event VaultAuthorized(address indexed vault);\n\n /// Emitted when a vault is deauthorized.\n /// @param vault Address of the vault.\n event VaultDeauthorized(address indexed vault);\n\n /// Emitted when tBTC is routed to a vault.\n /// @param vault Address of the vault.\n /// @param amount Amount of tBTC.\n /// @param sharesOut Amount of received shares.\n event DepositAllocated(\n address indexed vault,\n uint256 amount,\n uint256 sharesOut\n );\n\n /// Emitted when the maintainer address is updated.\n /// @param maintainer Address of the new maintainer.\n event MaintainerUpdated(address indexed maintainer);\n\n /// Reverts if the vault is already authorized.\n error VaultAlreadyAuthorized();\n\n /// Reverts if the vault is not authorized.\n error VaultUnauthorized();\n\n /// Reverts if the caller is not the maintainer.\n error NotMaintainer();\n\n /// Reverts if the address is zero.\n error ZeroAddress();\n\n /// Modifier that reverts if the caller is not the maintainer.\n modifier onlyMaintainer() {\n if (msg.sender != maintainer) {\n revert NotMaintainer();\n }\n _;\n }\n\n constructor(stBTC _stbtc, IERC20 _tbtc) Ownable(msg.sender) {\n stbtc = _stbtc;\n tbtc = _tbtc;\n }\n\n /// @notice Adds a vault to the list of authorized vaults.\n /// @param vault Address of the vault to add.\n function authorizeVault(address vault) external onlyOwner {\n if (isVaultAuthorized(vault)) {\n revert VaultAlreadyAuthorized();\n }\n\n vaults.push(vault);\n vaultsInfo[vault].authorized = true;\n\n emit VaultAuthorized(vault);\n }\n\n /// @notice Removes a vault from the list of authorized vaults.\n /// @param vault Address of the vault to remove.\n function deauthorizeVault(address vault) external onlyOwner {\n if (!isVaultAuthorized(vault)) {\n revert VaultUnauthorized();\n }\n\n vaultsInfo[vault].authorized = false;\n\n for (uint256 i = 0; i < vaults.length; i++) {\n if (vaults[i] == vault) {\n vaults[i] = vaults[vaults.length - 1];\n // slither-disable-next-line costly-loop\n vaults.pop();\n break;\n }\n }\n\n emit VaultDeauthorized(vault);\n }\n\n /// @notice Updates the maintainer address.\n /// @param newMaintainer Address of the new maintainer.\n function updateMaintainer(address newMaintainer) external onlyOwner {\n if (newMaintainer == address(0)) {\n revert ZeroAddress();\n }\n\n maintainer = newMaintainer;\n\n emit MaintainerUpdated(maintainer);\n }\n\n /// TODO: make this function internal once the allocation distribution is\n /// implemented\n /// @notice Routes tBTC from stBTC to a vault. Can be called by the maintainer\n /// only.\n /// @param vault Address of the vault to route the assets to.\n /// @param amount Amount of tBTC to deposit.\n /// @param minSharesOut Minimum amount of shares to receive.\n function depositToVault(\n address vault,\n uint256 amount,\n uint256 minSharesOut\n ) public onlyMaintainer {\n if (!isVaultAuthorized(vault)) {\n revert VaultUnauthorized();\n }\n\n // slither-disable-next-line arbitrary-send-erc20\n tbtc.safeTransferFrom(address(stbtc), address(this), amount);\n tbtc.forceApprove(address(vault), amount);\n\n uint256 sharesOut = deposit(\n IERC4626(vault),\n address(stbtc),\n amount,\n minSharesOut\n );\n // slither-disable-next-line reentrancy-events\n emit DepositAllocated(vault, amount, sharesOut);\n }\n\n /// @notice Returns the list of authorized vaults.\n function getVaults() public view returns (address[] memory) {\n return vaults;\n }\n\n /// @notice Returns true if the vault is authorized.\n /// @param vault Address of the vault to check.\n function isVaultAuthorized(address vault) public view returns (bool) {\n return vaultsInfo[vault].authorized;\n }\n\n /// TODO: implement redeem() / withdraw() functions\n}\n" - }, - "contracts/Router.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\n\n/// @title Router\n/// @notice Router is a contract that routes tBTC from stBTC to\n/// a given vault and back. Vaults supply yield strategies with tBTC that\n/// generate yield for Bitcoin holders.\nabstract contract Router {\n /// Thrown when amount of shares received is below the min set by caller.\n /// @param vault Address of the vault.\n /// @param sharesOut Amount of received shares.\n /// @param minSharesOut Minimum amount of shares expected to receive.\n error MinSharesError(\n address vault,\n uint256 sharesOut,\n uint256 minSharesOut\n );\n\n /// @notice Routes funds from stBTC to a vault. The amount of tBTC to\n /// Shares of deposited tBTC are minted to the stBTC contract.\n /// @param vault Address of the vault to route the funds to.\n /// @param receiver Address of the receiver of the shares.\n /// @param amount Amount of tBTC to deposit.\n /// @param minSharesOut Minimum amount of shares to receive.\n function deposit(\n IERC4626 vault,\n address receiver,\n uint256 amount,\n uint256 minSharesOut\n ) internal returns (uint256 sharesOut) {\n if ((sharesOut = vault.deposit(amount, receiver)) < minSharesOut) {\n revert MinSharesError(address(vault), sharesOut, minSharesOut);\n }\n }\n}\n" - }, - "contracts/stBTC.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/access/Ownable2Step.sol\";\nimport \"./Dispatcher.sol\";\n\n/// @title stBTC\n/// @notice This contract implements the ERC-4626 tokenized vault standard. By\n/// staking tBTC, users acquire a liquid staking token called stBTC,\n/// commonly referred to as \"shares\". The staked tBTC is securely\n/// deposited into Acre's vaults, where it generates yield over time.\n/// Users have the flexibility to redeem stBTC, enabling them to\n/// withdraw their staked tBTC along with the accrued yield.\n/// @dev ERC-4626 is a standard to optimize and unify the technical parameters\n/// of yield-bearing vaults. This contract facilitates the minting and\n/// burning of shares (stBTC), which are represented as standard ERC20\n/// tokens, providing a seamless exchange with tBTC tokens.\ncontract stBTC is ERC4626, Ownable2Step {\n using SafeERC20 for IERC20;\n\n /// Dispatcher contract that routes tBTC from stBTC to a given vault and back.\n Dispatcher public dispatcher;\n\n /// Address of the treasury wallet, where fees should be transferred to.\n address public treasury;\n\n /// Minimum amount for a single deposit operation. The value should be set\n /// low enough so the deposits routed through Bitcoin Depositor contract won't\n /// be rejected. It means that minimumDepositAmount should be lower than\n /// tBTC protocol's depositDustThreshold reduced by all the minting fees taken\n /// before depositing in the Acre contract.\n uint256 public minimumDepositAmount;\n\n /// Maximum total amount of tBTC token held by Acre protocol.\n uint256 public maximumTotalAssets;\n\n /// Emitted when the treasury wallet address is updated.\n /// @param treasury New treasury wallet address.\n event TreasuryUpdated(address treasury);\n\n /// Emitted when deposit parameters are updated.\n /// @param minimumDepositAmount New value of the minimum deposit amount.\n /// @param maximumTotalAssets New value of the maximum total assets amount.\n event DepositParametersUpdated(\n uint256 minimumDepositAmount,\n uint256 maximumTotalAssets\n );\n\n /// Emitted when the dispatcher contract is updated.\n /// @param oldDispatcher Address of the old dispatcher contract.\n /// @param newDispatcher Address of the new dispatcher contract.\n event DispatcherUpdated(address oldDispatcher, address newDispatcher);\n\n /// Reverts if the amount is less than the minimum deposit amount.\n /// @param amount Amount to check.\n /// @param min Minimum amount to check 'amount' against.\n error LessThanMinDeposit(uint256 amount, uint256 min);\n\n /// Reverts if the address is zero.\n error ZeroAddress();\n\n /// Reverts if the address is disallowed.\n error DisallowedAddress();\n\n constructor(\n IERC20 _tbtc,\n address _treasury\n ) ERC4626(_tbtc) ERC20(\"Acre Staked Bitcoin\", \"stBTC\") Ownable(msg.sender) {\n if (address(_treasury) == address(0)) {\n revert ZeroAddress();\n }\n treasury = _treasury;\n // TODO: Revisit the exact values closer to the launch.\n minimumDepositAmount = 0.001 * 1e18; // 0.001 tBTC\n maximumTotalAssets = 25 * 1e18; // 25 tBTC\n }\n\n /// @notice Updates treasury wallet address.\n /// @param newTreasury New treasury wallet address.\n function updateTreasury(address newTreasury) external onlyOwner {\n // TODO: Introduce a parameters update process.\n if (newTreasury == address(0)) {\n revert ZeroAddress();\n }\n if (newTreasury == address(this)) {\n revert DisallowedAddress();\n }\n treasury = newTreasury;\n\n emit TreasuryUpdated(newTreasury);\n }\n\n /// @notice Updates deposit parameters.\n /// @dev To disable the limit for deposits, set the maximum total assets to\n /// maximum (`type(uint256).max`).\n /// @param _minimumDepositAmount New value of the minimum deposit amount. It\n /// is the minimum amount for a single deposit operation.\n /// @param _maximumTotalAssets New value of the maximum total assets amount.\n /// It is the maximum amount of the tBTC token that the Acre protocol\n /// can hold.\n function updateDepositParameters(\n uint256 _minimumDepositAmount,\n uint256 _maximumTotalAssets\n ) external onlyOwner {\n // TODO: Introduce a parameters update process.\n minimumDepositAmount = _minimumDepositAmount;\n maximumTotalAssets = _maximumTotalAssets;\n\n emit DepositParametersUpdated(\n _minimumDepositAmount,\n _maximumTotalAssets\n );\n }\n\n // TODO: Implement a governed upgrade process that initiates an update and\n // then finalizes it after a delay.\n /// @notice Updates the dispatcher contract and gives it an unlimited\n /// allowance to transfer staked tBTC.\n /// @param newDispatcher Address of the new dispatcher contract.\n function updateDispatcher(Dispatcher newDispatcher) external onlyOwner {\n if (address(newDispatcher) == address(0)) {\n revert ZeroAddress();\n }\n\n address oldDispatcher = address(dispatcher);\n\n emit DispatcherUpdated(oldDispatcher, address(newDispatcher));\n dispatcher = newDispatcher;\n\n // TODO: Once withdrawal/rebalancing is implemented, we need to revoke the\n // approval of the vaults share tokens from the old dispatcher and approve\n // a new dispatcher to manage the share tokens.\n\n if (oldDispatcher != address(0)) {\n // Setting allowance to zero for the old dispatcher\n IERC20(asset()).forceApprove(oldDispatcher, 0);\n }\n\n // Setting allowance to max for the new dispatcher\n IERC20(asset()).forceApprove(address(dispatcher), type(uint256).max);\n }\n\n /// @notice Mints shares to receiver by depositing exactly amount of\n /// tBTC tokens.\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\n /// which determines the minimum amount for a single deposit operation.\n /// The amount of the assets has to be pre-approved in the tBTC\n /// contract.\n /// @param assets Approved amount of tBTC tokens to deposit.\n /// @param receiver The address to which the shares will be minted.\n /// @return Minted shares.\n function deposit(\n uint256 assets,\n address receiver\n ) public override returns (uint256) {\n if (assets < minimumDepositAmount) {\n revert LessThanMinDeposit(assets, minimumDepositAmount);\n }\n\n return super.deposit(assets, receiver);\n }\n\n /// @notice Mints shares to receiver by depositing tBTC tokens.\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\n /// which determines the minimum amount for a single deposit operation.\n /// The amount of the assets has to be pre-approved in the tBTC\n /// contract.\n /// The msg.sender is required to grant approval for tBTC transfer.\n /// To determine the total assets amount necessary for approval\n /// corresponding to a given share amount, use the `previewMint` function.\n /// @param shares Amount of shares to mint.\n /// @param receiver The address to which the shares will be minted.\n function mint(\n uint256 shares,\n address receiver\n ) public override returns (uint256 assets) {\n if ((assets = super.mint(shares, receiver)) < minimumDepositAmount) {\n revert LessThanMinDeposit(assets, minimumDepositAmount);\n }\n }\n\n /// @notice Returns value of assets that would be exchanged for the amount of\n /// shares owned by the `account`.\n /// @param account Owner of shares.\n /// @return Assets amount.\n function assetsBalanceOf(address account) public view returns (uint256) {\n return convertToAssets(balanceOf(account));\n }\n\n /// @notice Returns the maximum amount of the tBTC token that can be\n /// deposited into the vault for the receiver through a deposit\n /// call. It takes into account the deposit parameter, maximum total\n /// assets, which determines the total amount of tBTC token held by\n /// Acre protocol.\n /// @dev When the remaining amount of unused limit is less than the minimum\n /// deposit amount, this function returns 0.\n /// @return The maximum amount of tBTC token that can be deposited into\n /// Acre protocol for the receiver.\n function maxDeposit(address) public view override returns (uint256) {\n if (maximumTotalAssets == type(uint256).max) {\n return type(uint256).max;\n }\n\n uint256 _totalAssets = totalAssets();\n\n return\n _totalAssets >= maximumTotalAssets\n ? 0\n : maximumTotalAssets - _totalAssets;\n }\n\n /// @notice Returns the maximum amount of the vault shares that can be\n /// minted for the receiver, through a mint call.\n /// @dev Since the stBTC contract limits the maximum total tBTC tokens this\n /// function converts the maximum deposit amount to shares.\n /// @return The maximum amount of the vault shares.\n function maxMint(address receiver) public view override returns (uint256) {\n uint256 _maxDeposit = maxDeposit(receiver);\n\n // slither-disable-next-line incorrect-equality\n return\n _maxDeposit == type(uint256).max\n ? type(uint256).max\n : convertToShares(_maxDeposit);\n }\n\n /// @return Returns deposit parameters.\n function depositParameters() public view returns (uint256, uint256) {\n return (minimumDepositAmount, maximumTotalAssets);\n }\n}\n" - }, - "contracts/test/AcreBitcoinDepositor.t.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport {AcreBitcoinDepositor} from \"../AcreBitcoinDepositor.sol\";\n\n/// @dev A test contract to expose internal function from AcreBitcoinDepositor contract.\n/// This solution follows Foundry recommendation:\n/// https://book.getfoundry.sh/tutorials/best-practices#internal-functions\ncontract AcreBitcoinDepositorHarness is AcreBitcoinDepositor {\n constructor(\n address bridge,\n address tbtcVault,\n address tbtcToken,\n address stbtc\n ) AcreBitcoinDepositor(bridge, tbtcVault, tbtcToken, stbtc) {}\n\n function exposed_finalizeBridging(\n uint256 depositKey\n ) external returns (uint256 amountToStake, address staker) {\n return finalizeBridging(depositKey);\n }\n}\n" - }, - "contracts/test/MockTbtcBridge.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport {MockBridge, MockTBTCVault} from \"@keep-network/tbtc-v2/contracts/test/TestTBTCDepositor.sol\";\nimport {IBridge} from \"@keep-network/tbtc-v2/contracts/integrator/IBridge.sol\";\nimport {IBridgeTypes} from \"@keep-network/tbtc-v2/contracts/integrator/IBridge.sol\";\n\nimport {TestERC20} from \"./TestERC20.sol\";\n\ncontract BridgeStub is MockBridge {}\n\ncontract TBTCVaultStub is MockTBTCVault {\n TestERC20 public immutable tbtc;\n IBridge public immutable bridge;\n\n /// @notice Multiplier to convert satoshi to TBTC token units.\n uint256 public constant SATOSHI_MULTIPLIER = 10 ** 10;\n\n constructor(TestERC20 _tbtc, IBridge _bridge) {\n tbtc = _tbtc;\n bridge = _bridge;\n }\n\n function finalizeOptimisticMintingRequest(\n uint256 depositKey\n ) public override {\n IBridgeTypes.DepositRequest memory deposit = bridge.deposits(\n depositKey\n );\n\n uint256 amountSubTreasury = (deposit.amount - deposit.treasuryFee) *\n SATOSHI_MULTIPLIER;\n\n uint256 omFee = optimisticMintingFeeDivisor > 0\n ? (amountSubTreasury / optimisticMintingFeeDivisor)\n : 0;\n\n // The deposit transaction max fee is in the 1e8 satoshi precision.\n // We need to convert them to the 1e18 TBTC precision.\n // slither-disable-next-line unused-return\n (, , uint64 depositTxMaxFee, ) = bridge.depositParameters();\n uint256 txMaxFee = depositTxMaxFee * SATOSHI_MULTIPLIER;\n\n uint256 amountToMint = amountSubTreasury - omFee - txMaxFee;\n\n finalizeOptimisticMintingRequestWithAmount(depositKey, amountToMint);\n }\n\n function finalizeOptimisticMintingRequestWithAmount(\n uint256 depositKey,\n uint256 amountToMint\n ) public {\n MockTBTCVault.finalizeOptimisticMintingRequest(depositKey);\n\n tbtc.mint(bridge.deposits(depositKey).depositor, amountToMint);\n }\n}\n" - }, - "contracts/test/TestERC20.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract TestERC20 is ERC20 {\n constructor(string memory name, string memory symbol) ERC20(name, symbol) {}\n\n function mint(address account, uint256 value) external {\n _mint(account, value);\n }\n}\n" - } - }, - "settings": { - "optimizer": { - "enabled": true, - "runs": 1000 - }, - "evmVersion": "paris", - "outputSelection": { - "*": { - "*": [ - "abi", - "evm.bytecode", - "evm.deployedBytecode", - "evm.methodIdentifiers", - "metadata", - "devdoc", - "userdoc", - "storageLayout", - "evm.gasEstimates" - ], - "": [ - "ast" - ] - } - }, - "metadata": { - "useLiteralContent": true - } - } -} \ No newline at end of file diff --git a/solidity/deployments/sepolia/solcInputs/b22c277b248ba02f9ec5bf62d176f9ce.json b/solidity/deployments/sepolia/solcInputs/b22c277b248ba02f9ec5bf62d176f9ce.json deleted file mode 100644 index 0ee23a5b9..000000000 --- a/solidity/deployments/sepolia/solcInputs/b22c277b248ba02f9ec5bf62d176f9ce.json +++ /dev/null @@ -1,114 +0,0 @@ -{ - "language": "Solidity", - "sources": { - "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol": { - "content": "pragma solidity ^0.8.4;\n\n/** @title BitcoinSPV */\n/** @author Summa (https://summa.one) */\n\nimport {BytesLib} from \"./BytesLib.sol\";\nimport {SafeMath} from \"./SafeMath.sol\";\n\nlibrary BTCUtils {\n using BytesLib for bytes;\n using SafeMath for uint256;\n\n // The target at minimum Difficulty. Also the target of the genesis block\n uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000;\n\n uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds\n uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks\n\n uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n /* ***** */\n /* UTILS */\n /* ***** */\n\n /// @notice Determines the length of a VarInt in bytes\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\n /// @param _flag The first byte of a VarInt\n /// @return The number of non-flag bytes in the VarInt\n function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) {\n return determineVarIntDataLengthAt(_flag, 0);\n }\n\n /// @notice Determines the length of a VarInt in bytes\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\n /// @param _b The byte array containing a VarInt\n /// @param _at The position of the VarInt in the array\n /// @return The number of non-flag bytes in the VarInt\n function determineVarIntDataLengthAt(bytes memory _b, uint256 _at) internal pure returns (uint8) {\n if (uint8(_b[_at]) == 0xff) {\n return 8; // one-byte flag, 8 bytes data\n }\n if (uint8(_b[_at]) == 0xfe) {\n return 4; // one-byte flag, 4 bytes data\n }\n if (uint8(_b[_at]) == 0xfd) {\n return 2; // one-byte flag, 2 bytes data\n }\n\n return 0; // flag is data\n }\n\n /// @notice Parse a VarInt into its data length and the number it represents\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\n /// Caller SHOULD explicitly handle this case (or bubble it up)\n /// @param _b A byte-string starting with a VarInt\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\n function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) {\n return parseVarIntAt(_b, 0);\n }\n\n /// @notice Parse a VarInt into its data length and the number it represents\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\n /// Caller SHOULD explicitly handle this case (or bubble it up)\n /// @param _b A byte-string containing a VarInt\n /// @param _at The position of the VarInt\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\n function parseVarIntAt(bytes memory _b, uint256 _at) internal pure returns (uint256, uint256) {\n uint8 _dataLen = determineVarIntDataLengthAt(_b, _at);\n\n if (_dataLen == 0) {\n return (0, uint8(_b[_at]));\n }\n if (_b.length < 1 + _dataLen + _at) {\n return (ERR_BAD_ARG, 0);\n }\n uint256 _number;\n if (_dataLen == 2) {\n _number = reverseUint16(uint16(_b.slice2(1 + _at)));\n } else if (_dataLen == 4) {\n _number = reverseUint32(uint32(_b.slice4(1 + _at)));\n } else if (_dataLen == 8) {\n _number = reverseUint64(uint64(_b.slice8(1 + _at)));\n }\n return (_dataLen, _number);\n }\n\n /// @notice Changes the endianness of a byte array\n /// @dev Returns a new, backwards, bytes\n /// @param _b The bytes to reverse\n /// @return The reversed bytes\n function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) {\n bytes memory _newValue = new bytes(_b.length);\n\n for (uint i = 0; i < _b.length; i++) {\n _newValue[_b.length - i - 1] = _b[i];\n }\n\n return _newValue;\n }\n\n /// @notice Changes the endianness of a uint256\n /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint256(uint256 _b) internal pure returns (uint256 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |\n ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);\n // swap 2-byte long pairs\n v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |\n ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);\n // swap 4-byte long pairs\n v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |\n ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);\n // swap 8-byte long pairs\n v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |\n ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);\n // swap 16-byte long pairs\n v = (v >> 128) | (v << 128);\n }\n\n /// @notice Changes the endianness of a uint64\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint64(uint64 _b) internal pure returns (uint64 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF00FF00FF) |\n ((v & 0x00FF00FF00FF00FF) << 8);\n // swap 2-byte long pairs\n v = ((v >> 16) & 0x0000FFFF0000FFFF) |\n ((v & 0x0000FFFF0000FFFF) << 16);\n // swap 4-byte long pairs\n v = (v >> 32) | (v << 32);\n }\n\n /// @notice Changes the endianness of a uint32\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint32(uint32 _b) internal pure returns (uint32 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF) |\n ((v & 0x00FF00FF) << 8);\n // swap 2-byte long pairs\n v = (v >> 16) | (v << 16);\n }\n\n /// @notice Changes the endianness of a uint24\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint24(uint24 _b) internal pure returns (uint24 v) {\n v = (_b << 16) | (_b & 0x00FF00) | (_b >> 16);\n }\n\n /// @notice Changes the endianness of a uint16\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint16(uint16 _b) internal pure returns (uint16 v) {\n v = (_b << 8) | (_b >> 8);\n }\n\n\n /// @notice Converts big-endian bytes to a uint\n /// @dev Traverses the byte array and sums the bytes\n /// @param _b The big-endian bytes-encoded integer\n /// @return The integer representation\n function bytesToUint(bytes memory _b) internal pure returns (uint256) {\n uint256 _number;\n\n for (uint i = 0; i < _b.length; i++) {\n _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));\n }\n\n return _number;\n }\n\n /// @notice Get the last _num bytes from a byte array\n /// @param _b The byte array to slice\n /// @param _num The number of bytes to extract from the end\n /// @return The last _num bytes of _b\n function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) {\n uint256 _start = _b.length.sub(_num);\n\n return _b.slice(_start, _num);\n }\n\n /// @notice Implements bitcoin's hash160 (rmd160(sha2()))\n /// @dev abi.encodePacked changes the return to bytes instead of bytes32\n /// @param _b The pre-image\n /// @return The digest\n function hash160(bytes memory _b) internal pure returns (bytes memory) {\n return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));\n }\n\n /// @notice Implements bitcoin's hash160 (sha2 + ripemd160)\n /// @dev sha2 precompile at address(2), ripemd160 at address(3)\n /// @param _b The pre-image\n /// @return res The digest\n function hash160View(bytes memory _b) internal view returns (bytes20 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\n pop(staticcall(gas(), 3, 0x00, 32, 0x00, 32))\n // read from position 12 = 0c\n res := mload(0x0c)\n }\n }\n\n /// @notice Implements bitcoin's hash256 (double sha2)\n /// @dev abi.encodePacked changes the return to bytes instead of bytes32\n /// @param _b The pre-image\n /// @return The digest\n function hash256(bytes memory _b) internal pure returns (bytes32) {\n return sha256(abi.encodePacked(sha256(_b)));\n }\n\n /// @notice Implements bitcoin's hash256 (double sha2)\n /// @dev sha2 is precompiled smart contract located at address(2)\n /// @param _b The pre-image\n /// @return res The digest\n function hash256View(bytes memory _b) internal view returns (bytes32 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\n res := mload(0x00)\n }\n }\n\n /// @notice Implements bitcoin's hash256 on a pair of bytes32\n /// @dev sha2 is precompiled smart contract located at address(2)\n /// @param _a The first bytes32 of the pre-image\n /// @param _b The second bytes32 of the pre-image\n /// @return res The digest\n function hash256Pair(bytes32 _a, bytes32 _b) internal view returns (bytes32 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n mstore(0x00, _a)\n mstore(0x20, _b)\n pop(staticcall(gas(), 2, 0x00, 64, 0x00, 32))\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\n res := mload(0x00)\n }\n }\n\n /// @notice Implements bitcoin's hash256 (double sha2)\n /// @dev sha2 is precompiled smart contract located at address(2)\n /// @param _b The array containing the pre-image\n /// @param at The start of the pre-image\n /// @param len The length of the pre-image\n /// @return res The digest\n function hash256Slice(\n bytes memory _b,\n uint256 at,\n uint256 len\n ) internal view returns (bytes32 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n pop(staticcall(gas(), 2, add(_b, add(32, at)), len, 0x00, 32))\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\n res := mload(0x00)\n }\n }\n\n /* ************ */\n /* Legacy Input */\n /* ************ */\n\n /// @notice Extracts the nth input from the vin (0-indexed)\n /// @dev Iterates over the vin. If you need to extract several, write a custom function\n /// @param _vin The vin as a tightly-packed byte array\n /// @param _index The 0-indexed location of the input to extract\n /// @return The input as a byte array\n function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _nIns;\n\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\n require(_varIntDataLen != ERR_BAD_ARG, \"Read overrun during VarInt parsing\");\n require(_index < _nIns, \"Vin read overrun\");\n\n uint256 _len = 0;\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 _i = 0; _i < _index; _i ++) {\n _len = determineInputLengthAt(_vin, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n _offset = _offset + _len;\n }\n\n _len = determineInputLengthAt(_vin, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _vin.slice(_offset, _len);\n }\n\n /// @notice Determines whether an input is legacy\n /// @dev False if no scriptSig, otherwise True\n /// @param _input The input\n /// @return True for legacy, False for witness\n function isLegacyInput(bytes memory _input) internal pure returns (bool) {\n return _input[36] != hex\"00\";\n }\n\n /// @notice Determines the length of a scriptSig in an input\n /// @dev Will return 0 if passed a witness input.\n /// @param _input The LEGACY input\n /// @return The length of the script sig\n function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) {\n return extractScriptSigLenAt(_input, 0);\n }\n\n /// @notice Determines the length of a scriptSig in an input\n /// starting at the specified position\n /// @dev Will return 0 if passed a witness input.\n /// @param _input The byte array containing the LEGACY input\n /// @param _at The position of the input in the array\n /// @return The length of the script sig\n function extractScriptSigLenAt(bytes memory _input, uint256 _at) internal pure returns (uint256, uint256) {\n if (_input.length < 37 + _at) {\n return (ERR_BAD_ARG, 0);\n }\n\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = parseVarIntAt(_input, _at + 36);\n\n return (_varIntDataLen, _scriptSigLen);\n }\n\n /// @notice Determines the length of an input from its scriptSig\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\n /// @param _input The input\n /// @return The length of the input in bytes\n function determineInputLength(bytes memory _input) internal pure returns (uint256) {\n return determineInputLengthAt(_input, 0);\n }\n\n /// @notice Determines the length of an input from its scriptSig,\n /// starting at the specified position\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\n /// @param _input The byte array containing the input\n /// @param _at The position of the input in the array\n /// @return The length of the input in bytes\n function determineInputLengthAt(bytes memory _input, uint256 _at) internal pure returns (uint256) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLenAt(_input, _at);\n if (_varIntDataLen == ERR_BAD_ARG) {\n return ERR_BAD_ARG;\n }\n\n return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;\n }\n\n /// @notice Extracts the LE sequence bytes from an input\n /// @dev Sequence is used for relative time locks\n /// @param _input The LEGACY input\n /// @return The sequence bytes (LE uint)\n function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes4) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\n require(_varIntDataLen != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _input.slice4(36 + 1 + _varIntDataLen + _scriptSigLen);\n }\n\n /// @notice Extracts the sequence from the input\n /// @dev Sequence is a 4-byte little-endian number\n /// @param _input The LEGACY input\n /// @return The sequence number (big-endian uint)\n function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) {\n uint32 _leSeqence = uint32(extractSequenceLELegacy(_input));\n uint32 _beSequence = reverseUint32(_leSeqence);\n return _beSequence;\n }\n /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx\n /// @dev Will return hex\"00\" if passed a witness input\n /// @param _input The LEGACY input\n /// @return The length-prepended scriptSig\n function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\n require(_varIntDataLen != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);\n }\n\n\n /* ************* */\n /* Witness Input */\n /* ************* */\n\n /// @notice Extracts the LE sequence bytes from an input\n /// @dev Sequence is used for relative time locks\n /// @param _input The WITNESS input\n /// @return The sequence bytes (LE uint)\n function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes4) {\n return _input.slice4(37);\n }\n\n /// @notice Extracts the sequence from the input in a tx\n /// @dev Sequence is a 4-byte little-endian number\n /// @param _input The WITNESS input\n /// @return The sequence number (big-endian uint)\n function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) {\n uint32 _leSeqence = uint32(extractSequenceLEWitness(_input));\n uint32 _inputeSequence = reverseUint32(_leSeqence);\n return _inputeSequence;\n }\n\n /// @notice Extracts the outpoint from the input in a tx\n /// @dev 32-byte tx id with 4-byte index\n /// @param _input The input\n /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)\n function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) {\n return _input.slice(0, 36);\n }\n\n /// @notice Extracts the outpoint tx id from an input\n /// @dev 32-byte tx id\n /// @param _input The input\n /// @return The tx id (little-endian bytes)\n function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) {\n return _input.slice32(0);\n }\n\n /// @notice Extracts the outpoint tx id from an input\n /// starting at the specified position\n /// @dev 32-byte tx id\n /// @param _input The byte array containing the input\n /// @param _at The position of the input\n /// @return The tx id (little-endian bytes)\n function extractInputTxIdLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes32) {\n return _input.slice32(_at);\n }\n\n /// @notice Extracts the LE tx input index from the input in a tx\n /// @dev 4-byte tx index\n /// @param _input The input\n /// @return The tx index (little-endian bytes)\n function extractTxIndexLE(bytes memory _input) internal pure returns (bytes4) {\n return _input.slice4(32);\n }\n\n /// @notice Extracts the LE tx input index from the input in a tx\n /// starting at the specified position\n /// @dev 4-byte tx index\n /// @param _input The byte array containing the input\n /// @param _at The position of the input\n /// @return The tx index (little-endian bytes)\n function extractTxIndexLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes4) {\n return _input.slice4(32 + _at);\n }\n\n /* ****** */\n /* Output */\n /* ****** */\n\n /// @notice Determines the length of an output\n /// @dev Works with any properly formatted output\n /// @param _output The output\n /// @return The length indicated by the prefix, error if invalid length\n function determineOutputLength(bytes memory _output) internal pure returns (uint256) {\n return determineOutputLengthAt(_output, 0);\n }\n\n /// @notice Determines the length of an output\n /// starting at the specified position\n /// @dev Works with any properly formatted output\n /// @param _output The byte array containing the output\n /// @param _at The position of the output\n /// @return The length indicated by the prefix, error if invalid length\n function determineOutputLengthAt(bytes memory _output, uint256 _at) internal pure returns (uint256) {\n if (_output.length < 9 + _at) {\n return ERR_BAD_ARG;\n }\n uint256 _varIntDataLen;\n uint256 _scriptPubkeyLength;\n (_varIntDataLen, _scriptPubkeyLength) = parseVarIntAt(_output, 8 + _at);\n\n if (_varIntDataLen == ERR_BAD_ARG) {\n return ERR_BAD_ARG;\n }\n\n // 8-byte value, 1-byte for tag itself\n return 8 + 1 + _varIntDataLen + _scriptPubkeyLength;\n }\n\n /// @notice Extracts the output at a given index in the TxOuts vector\n /// @dev Iterates over the vout. If you need to extract multiple, write a custom function\n /// @param _vout The _vout to extract from\n /// @param _index The 0-indexed location of the output to extract\n /// @return The specified output\n function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _nOuts;\n\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\n require(_varIntDataLen != ERR_BAD_ARG, \"Read overrun during VarInt parsing\");\n require(_index < _nOuts, \"Vout read overrun\");\n\n uint256 _len = 0;\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 _i = 0; _i < _index; _i ++) {\n _len = determineOutputLengthAt(_vout, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptPubkey\");\n _offset += _len;\n }\n\n _len = determineOutputLengthAt(_vout, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptPubkey\");\n return _vout.slice(_offset, _len);\n }\n\n /// @notice Extracts the value bytes from the output in a tx\n /// @dev Value is an 8-byte little-endian number\n /// @param _output The output\n /// @return The output value as LE bytes\n function extractValueLE(bytes memory _output) internal pure returns (bytes8) {\n return _output.slice8(0);\n }\n\n /// @notice Extracts the value from the output in a tx\n /// @dev Value is an 8-byte little-endian number\n /// @param _output The output\n /// @return The output value\n function extractValue(bytes memory _output) internal pure returns (uint64) {\n uint64 _leValue = uint64(extractValueLE(_output));\n uint64 _beValue = reverseUint64(_leValue);\n return _beValue;\n }\n\n /// @notice Extracts the value from the output in a tx\n /// @dev Value is an 8-byte little-endian number\n /// @param _output The byte array containing the output\n /// @param _at The starting index of the output in the array\n /// @return The output value\n function extractValueAt(bytes memory _output, uint256 _at) internal pure returns (uint64) {\n uint64 _leValue = uint64(_output.slice8(_at));\n uint64 _beValue = reverseUint64(_leValue);\n return _beValue;\n }\n\n /// @notice Extracts the data from an op return output\n /// @dev Returns hex\"\" if no data or not an op return\n /// @param _output The output\n /// @return Any data contained in the opreturn output, null if not an op return\n function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) {\n if (_output[9] != hex\"6a\") {\n return hex\"\";\n }\n bytes1 _dataLen = _output[10];\n return _output.slice(11, uint256(uint8(_dataLen)));\n }\n\n /// @notice Extracts the hash from the output script\n /// @dev Determines type by the length prefix and validates format\n /// @param _output The output\n /// @return The hash committed to by the pk_script, or null for errors\n function extractHash(bytes memory _output) internal pure returns (bytes memory) {\n return extractHashAt(_output, 8, _output.length - 8);\n }\n\n /// @notice Extracts the hash from the output script\n /// @dev Determines type by the length prefix and validates format\n /// @param _output The byte array containing the output\n /// @param _at The starting index of the output script in the array\n /// (output start + 8)\n /// @param _len The length of the output script\n /// (output length - 8)\n /// @return The hash committed to by the pk_script, or null for errors\n function extractHashAt(\n bytes memory _output,\n uint256 _at,\n uint256 _len\n ) internal pure returns (bytes memory) {\n uint8 _scriptLen = uint8(_output[_at]);\n\n // don't have to worry about overflow here.\n // if _scriptLen + 1 overflows, then output length would have to be < 1\n // for this check to pass. if it's < 1, then we errored when assigning\n // _scriptLen\n if (_scriptLen + 1 != _len) {\n return hex\"\";\n }\n\n if (uint8(_output[_at + 1]) == 0) {\n if (_scriptLen < 2) {\n return hex\"\";\n }\n uint256 _payloadLen = uint8(_output[_at + 2]);\n // Check for maliciously formatted witness outputs.\n // No need to worry about underflow as long b/c of the `< 2` check\n if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) {\n return hex\"\";\n }\n return _output.slice(_at + 3, _payloadLen);\n } else {\n bytes3 _tag = _output.slice3(_at);\n // p2pkh\n if (_tag == hex\"1976a9\") {\n // Check for maliciously formatted p2pkh\n // No need to worry about underflow, b/c of _scriptLen check\n if (uint8(_output[_at + 3]) != 0x14 ||\n _output.slice2(_at + _len - 2) != hex\"88ac\") {\n return hex\"\";\n }\n return _output.slice(_at + 4, 20);\n //p2sh\n } else if (_tag == hex\"17a914\") {\n // Check for maliciously formatted p2sh\n // No need to worry about underflow, b/c of _scriptLen check\n if (uint8(_output[_at + _len - 1]) != 0x87) {\n return hex\"\";\n }\n return _output.slice(_at + 3, 20);\n }\n }\n return hex\"\"; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */\n }\n\n /* ********** */\n /* Witness TX */\n /* ********** */\n\n\n /// @notice Checks that the vin passed up is properly formatted\n /// @dev Consider a vin with a valid vout in its scriptsig\n /// @param _vin Raw bytes length-prefixed input vector\n /// @return True if it represents a validly formatted vin\n function validateVin(bytes memory _vin) internal pure returns (bool) {\n uint256 _varIntDataLen;\n uint256 _nIns;\n\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\n\n // Not valid if it says there are too many or no inputs\n if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) {\n return false;\n }\n\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 i = 0; i < _nIns; i++) {\n // If we're at the end, but still expect more\n if (_offset >= _vin.length) {\n return false;\n }\n\n // Grab the next input and determine its length.\n uint256 _nextLen = determineInputLengthAt(_vin, _offset);\n if (_nextLen == ERR_BAD_ARG) {\n return false;\n }\n\n // Increase the offset by that much\n _offset += _nextLen;\n }\n\n // Returns false if we're not exactly at the end\n return _offset == _vin.length;\n }\n\n /// @notice Checks that the vout passed up is properly formatted\n /// @dev Consider a vout with a valid scriptpubkey\n /// @param _vout Raw bytes length-prefixed output vector\n /// @return True if it represents a validly formatted vout\n function validateVout(bytes memory _vout) internal pure returns (bool) {\n uint256 _varIntDataLen;\n uint256 _nOuts;\n\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\n\n // Not valid if it says there are too many or no outputs\n if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) {\n return false;\n }\n\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 i = 0; i < _nOuts; i++) {\n // If we're at the end, but still expect more\n if (_offset >= _vout.length) {\n return false;\n }\n\n // Grab the next output and determine its length.\n // Increase the offset by that much\n uint256 _nextLen = determineOutputLengthAt(_vout, _offset);\n if (_nextLen == ERR_BAD_ARG) {\n return false;\n }\n\n _offset += _nextLen;\n }\n\n // Returns false if we're not exactly at the end\n return _offset == _vout.length;\n }\n\n\n\n /* ************ */\n /* Block Header */\n /* ************ */\n\n /// @notice Extracts the transaction merkle root from a block header\n /// @dev Use verifyHash256Merkle to verify proofs with this root\n /// @param _header The header\n /// @return The merkle root (little-endian)\n function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes32) {\n return _header.slice32(36);\n }\n\n /// @notice Extracts the target from a block header\n /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\n /// @param _header The header\n /// @return The target threshold\n function extractTarget(bytes memory _header) internal pure returns (uint256) {\n return extractTargetAt(_header, 0);\n }\n\n /// @notice Extracts the target from a block header\n /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\n /// @param _header The array containing the header\n /// @param at The start of the header\n /// @return The target threshold\n function extractTargetAt(bytes memory _header, uint256 at) internal pure returns (uint256) {\n uint24 _m = uint24(_header.slice3(72 + at));\n uint8 _e = uint8(_header[75 + at]);\n uint256 _mantissa = uint256(reverseUint24(_m));\n uint _exponent = _e - 3;\n\n return _mantissa * (256 ** _exponent);\n }\n\n /// @notice Calculate difficulty from the difficulty 1 target and current target\n /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet\n /// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\n /// @param _target The current target\n /// @return The block difficulty (bdiff)\n function calculateDifficulty(uint256 _target) internal pure returns (uint256) {\n // Difficulty 1 calculated from 0x1d00ffff\n return DIFF1_TARGET.div(_target);\n }\n\n /// @notice Extracts the previous block's hash from a block header\n /// @dev Block headers do NOT include block number :(\n /// @param _header The header\n /// @return The previous block's hash (little-endian)\n function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes32) {\n return _header.slice32(4);\n }\n\n /// @notice Extracts the previous block's hash from a block header\n /// @dev Block headers do NOT include block number :(\n /// @param _header The array containing the header\n /// @param at The start of the header\n /// @return The previous block's hash (little-endian)\n function extractPrevBlockLEAt(\n bytes memory _header,\n uint256 at\n ) internal pure returns (bytes32) {\n return _header.slice32(4 + at);\n }\n\n /// @notice Extracts the timestamp from a block header\n /// @dev Time is not 100% reliable\n /// @param _header The header\n /// @return The timestamp (little-endian bytes)\n function extractTimestampLE(bytes memory _header) internal pure returns (bytes4) {\n return _header.slice4(68);\n }\n\n /// @notice Extracts the timestamp from a block header\n /// @dev Time is not 100% reliable\n /// @param _header The header\n /// @return The timestamp (uint)\n function extractTimestamp(bytes memory _header) internal pure returns (uint32) {\n return reverseUint32(uint32(extractTimestampLE(_header)));\n }\n\n /// @notice Extracts the expected difficulty from a block header\n /// @dev Does NOT verify the work\n /// @param _header The header\n /// @return The difficulty as an integer\n function extractDifficulty(bytes memory _header) internal pure returns (uint256) {\n return calculateDifficulty(extractTarget(_header));\n }\n\n /// @notice Concatenates and hashes two inputs for merkle proving\n /// @param _a The first hash\n /// @param _b The second hash\n /// @return The double-sha256 of the concatenated hashes\n function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal view returns (bytes32) {\n return hash256View(abi.encodePacked(_a, _b));\n }\n\n /// @notice Concatenates and hashes two inputs for merkle proving\n /// @param _a The first hash\n /// @param _b The second hash\n /// @return The double-sha256 of the concatenated hashes\n function _hash256MerkleStep(bytes32 _a, bytes32 _b) internal view returns (bytes32) {\n return hash256Pair(_a, _b);\n }\n\n\n /// @notice Verifies a Bitcoin-style merkle tree\n /// @dev Leaves are 0-indexed. Inefficient version.\n /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root\n /// @param _index The index of the leaf\n /// @return true if the proof is valid, else false\n function verifyHash256Merkle(bytes memory _proof, uint _index) internal view returns (bool) {\n // Not an even number of hashes\n if (_proof.length % 32 != 0) {\n return false;\n }\n\n // Special case for coinbase-only blocks\n if (_proof.length == 32) {\n return true;\n }\n\n // Should never occur\n if (_proof.length == 64) {\n return false;\n }\n\n bytes32 _root = _proof.slice32(_proof.length - 32);\n bytes32 _current = _proof.slice32(0);\n bytes memory _tree = _proof.slice(32, _proof.length - 64);\n\n return verifyHash256Merkle(_current, _tree, _root, _index);\n }\n\n /// @notice Verifies a Bitcoin-style merkle tree\n /// @dev Leaves are 0-indexed. Efficient version.\n /// @param _leaf The leaf of the proof. LE sha256 hash.\n /// @param _tree The intermediate nodes in the proof.\n /// Tightly packed LE sha256 hashes.\n /// @param _root The root of the proof. LE sha256 hash.\n /// @param _index The index of the leaf\n /// @return true if the proof is valid, else false\n function verifyHash256Merkle(\n bytes32 _leaf,\n bytes memory _tree,\n bytes32 _root,\n uint _index\n ) internal view returns (bool) {\n // Not an even number of hashes\n if (_tree.length % 32 != 0) {\n return false;\n }\n\n // Should never occur\n if (_tree.length == 0) {\n return false;\n }\n\n uint _idx = _index;\n bytes32 _current = _leaf;\n\n // i moves in increments of 32\n for (uint i = 0; i < _tree.length; i += 32) {\n if (_idx % 2 == 1) {\n _current = _hash256MerkleStep(_tree.slice32(i), _current);\n } else {\n _current = _hash256MerkleStep(_current, _tree.slice32(i));\n }\n _idx = _idx >> 1;\n }\n return _current == _root;\n }\n\n /*\n NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72\n NB: We get a full-bitlength target from this. For comparison with\n header-encoded targets we need to mask it with the header target\n e.g. (full & truncated) == truncated\n */\n /// @notice performs the bitcoin difficulty retarget\n /// @dev implements the Bitcoin algorithm precisely\n /// @param _previousTarget the target of the previous period\n /// @param _firstTimestamp the timestamp of the first block in the difficulty period\n /// @param _secondTimestamp the timestamp of the last block in the difficulty period\n /// @return the new period's target threshold\n function retargetAlgorithm(\n uint256 _previousTarget,\n uint256 _firstTimestamp,\n uint256 _secondTimestamp\n ) internal pure returns (uint256) {\n uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);\n\n // Normalize ratio to factor of 4 if very long or very short\n if (_elapsedTime < RETARGET_PERIOD.div(4)) {\n _elapsedTime = RETARGET_PERIOD.div(4);\n }\n if (_elapsedTime > RETARGET_PERIOD.mul(4)) {\n _elapsedTime = RETARGET_PERIOD.mul(4);\n }\n\n /*\n NB: high targets e.g. ffff0020 can cause overflows here\n so we divide it by 256**2, then multiply by 256**2 later\n we know the target is evenly divisible by 256**2, so this isn't an issue\n */\n\n uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);\n return _adjusted.div(RETARGET_PERIOD).mul(65536);\n }\n}\n" - }, - "@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol": { - "content": "pragma solidity ^0.8.4;\n\n/*\n\nhttps://github.com/GNSPS/solidity-bytes-utils/\n\nThis is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, compile, sell, or\ndistribute this software, either in source code form or as a compiled\nbinary, for any purpose, commercial or non-commercial, and by any\nmeans.\n\nIn jurisdictions that recognize copyright laws, the author or authors\nof this software dedicate any and all copyright interest in the\nsoftware to the public domain. We make this dedication for the benefit\nof the public at large and to the detriment of our heirs and\nsuccessors. We intend this dedication to be an overt act of\nrelinquishment in perpetuity of all present and future rights to this\nsoftware under copyright law.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n\nFor more information, please refer to \n*/\n\n\n/** @title BytesLib **/\n/** @author https://github.com/GNSPS **/\n\nlibrary BytesLib {\n function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {\n bytes memory tempBytes;\n\n assembly {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // Store the length of the first bytes array at the beginning of\n // the memory for tempBytes.\n let length := mload(_preBytes)\n mstore(tempBytes, length)\n\n // Maintain a memory counter for the current write location in the\n // temp bytes array by adding the 32 bytes for the array length to\n // the starting location.\n let mc := add(tempBytes, 0x20)\n // Stop copying when the memory counter reaches the length of the\n // first bytes array.\n let end := add(mc, length)\n\n for {\n // Initialize a copy counter to the start of the _preBytes data,\n // 32 bytes into its memory.\n let cc := add(_preBytes, 0x20)\n } lt(mc, end) {\n // Increase both counters by 32 bytes each iteration.\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // Write the _preBytes data into the tempBytes memory 32 bytes\n // at a time.\n mstore(mc, mload(cc))\n }\n\n // Add the length of _postBytes to the current length of tempBytes\n // and store it as the new length in the first 32 bytes of the\n // tempBytes memory.\n length := mload(_postBytes)\n mstore(tempBytes, add(length, mload(tempBytes)))\n\n // Move the memory counter back from a multiple of 0x20 to the\n // actual end of the _preBytes data.\n mc := end\n // Stop copying when the memory counter reaches the new combined\n // length of the arrays.\n end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n // Update the free-memory pointer by padding our last write location\n // to 32 bytes: add 31 bytes to the end of tempBytes to move to the\n // next 32 byte block, then round down to the nearest multiple of\n // 32. If the sum of the length of the two arrays is zero then add\n // one before rounding down to leave a blank 32 bytes (the length block with 0).\n mstore(0x40, and(\n add(add(end, iszero(add(length, mload(_preBytes)))), 31),\n not(31) // Round down to the nearest 32 bytes.\n ))\n }\n\n return tempBytes;\n }\n\n function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {\n assembly {\n // Read the first 32 bytes of _preBytes storage, which is the length\n // of the array. (We don't need to use the offset into the slot\n // because arrays use the entire slot.)\n let fslot := sload(_preBytes.slot)\n // Arrays of 31 bytes or less have an even value in their slot,\n // while longer arrays have an odd value. The actual length is\n // the slot divided by two for odd values, and the lowest order\n // byte divided by two for even values.\n // If the slot is even, bitwise and the slot with 255 and divide by\n // two to get the length. If the slot is odd, bitwise and the slot\n // with -1 and divide by two.\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n let newlength := add(slength, mlength)\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n switch add(lt(slength, 32), lt(newlength, 32))\n case 2 {\n // Since the new array still fits in the slot, we just need to\n // update the contents of the slot.\n // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length\n sstore(\n _preBytes.slot,\n // all the modifications to the slot are inside this\n // next block\n add(\n // we can just add to the slot contents because the\n // bytes we want to change are the LSBs\n fslot,\n add(\n mul(\n div(\n // load the bytes from memory\n mload(add(_postBytes, 0x20)),\n // zero all bytes to the right\n exp(0x100, sub(32, mlength))\n ),\n // and now shift left the number of bytes to\n // leave space for the length in the slot\n exp(0x100, sub(32, newlength))\n ),\n // increase length by the double of the memory\n // bytes length\n mul(mlength, 2)\n )\n )\n )\n }\n case 1 {\n // The stored value fits in the slot, but the combined value\n // will exceed it.\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // The contents of the _postBytes array start 32 bytes into\n // the structure. Our first read should obtain the `submod`\n // bytes that can fit into the unused space in the last word\n // of the stored array. To get this, we read 32 bytes starting\n // from `submod`, so the data we read overlaps with the array\n // contents by `submod` bytes. Masking the lowest-order\n // `submod` bytes allows us to add that value directly to the\n // stored value.\n\n let submod := sub(32, slength)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(\n sc,\n add(\n and(\n fslot,\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00\n ),\n and(mload(mc), mask)\n )\n )\n\n for {\n mc := add(mc, 0x20)\n sc := add(sc, 1)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n default {\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n // Start copying to the last used word of the stored array.\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // Copy over the first `submod` bytes of the new data as in\n // case 1 above.\n let slengthmod := mod(slength, 32)\n let mlengthmod := mod(mlength, 32)\n let submod := sub(32, slengthmod)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(sc, add(sload(sc), and(mload(mc), mask)))\n\n for {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n }\n }\n\n function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) {\n if (_length == 0) {\n return hex\"\";\n }\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n // Alloc bytes array with additional 32 bytes afterspace and assign it's size\n res := mload(0x40)\n mstore(0x40, add(add(res, 64), _length))\n mstore(res, _length)\n\n // Compute distance between source and destination pointers\n let diff := sub(res, add(_bytes, _start))\n\n for {\n let src := add(add(_bytes, 32), _start)\n let end := add(src, _length)\n } lt(src, end) {\n src := add(src, 32)\n } {\n mstore(add(src, diff), mload(src))\n }\n }\n }\n\n /// @notice Take a slice of the byte array, overwriting the destination.\n /// The length of the slice will equal the length of the destination array.\n /// @dev Make sure the destination array has afterspace if required.\n /// @param _bytes The source array\n /// @param _dest The destination array.\n /// @param _start The location to start in the source array.\n function sliceInPlace(\n bytes memory _bytes,\n bytes memory _dest,\n uint _start\n ) internal pure {\n uint _length = _dest.length;\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n for {\n let src := add(add(_bytes, 32), _start)\n let res := add(_dest, 32)\n let end := add(src, _length)\n } lt(src, end) {\n src := add(src, 32)\n res := add(res, 32)\n } {\n mstore(res, mload(src))\n }\n }\n }\n\n // Static slice functions, no bounds checking\n /// @notice take a 32-byte slice from the specified position\n function slice32(bytes memory _bytes, uint _start) internal pure returns (bytes32 res) {\n assembly {\n res := mload(add(add(_bytes, 32), _start))\n }\n }\n\n /// @notice take a 20-byte slice from the specified position\n function slice20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {\n return bytes20(slice32(_bytes, _start));\n }\n\n /// @notice take a 8-byte slice from the specified position\n function slice8(bytes memory _bytes, uint _start) internal pure returns (bytes8) {\n return bytes8(slice32(_bytes, _start));\n }\n\n /// @notice take a 4-byte slice from the specified position\n function slice4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {\n return bytes4(slice32(_bytes, _start));\n }\n\n /// @notice take a 3-byte slice from the specified position\n function slice3(bytes memory _bytes, uint _start) internal pure returns (bytes3) {\n return bytes3(slice32(_bytes, _start));\n }\n\n /// @notice take a 2-byte slice from the specified position\n function slice2(bytes memory _bytes, uint _start) internal pure returns (bytes2) {\n return bytes2(slice32(_bytes, _start));\n }\n\n function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {\n uint _totalLen = _start + 20;\n require(_totalLen > _start && _bytes.length >= _totalLen, \"Address conversion out of bounds.\");\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {\n uint _totalLen = _start + 32;\n require(_totalLen > _start && _bytes.length >= _totalLen, \"Uint conversion out of bounds.\");\n uint256 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x20), _start))\n }\n\n return tempUint;\n }\n\n function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {\n bool success = true;\n\n assembly {\n let length := mload(_preBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(length, mload(_postBytes))\n case 1 {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n let mc := add(_preBytes, 0x20)\n let end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n // the next line is the loop condition:\n // while(uint(mc < end) + cb == 2)\n } eq(add(lt(mc, end), cb), 2) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // if any of these checks fails then arrays are not equal\n if iszero(eq(mload(mc), mload(cc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {\n bool success = true;\n\n assembly {\n // we know _preBytes_offset is 0\n let fslot := sload(_preBytes.slot)\n // Decode the length of the stored array like in concatStorage().\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(slength, mlength)\n case 1 {\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n if iszero(iszero(slength)) {\n switch lt(slength, 32)\n case 1 {\n // blank the last byte which is the length\n fslot := mul(div(fslot, 0x100), 0x100)\n\n if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {\n // unsuccess:\n success := 0\n }\n }\n default {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := keccak256(0x0, 0x20)\n\n let mc := add(_postBytes, 0x20)\n let end := add(mc, mlength)\n\n // the next line is the loop condition:\n // while(uint(mc < end) + cb == 2)\n for {} eq(add(lt(mc, end), cb), 2) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n if iszero(eq(sload(sc), mload(mc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function toBytes32(bytes memory _source) pure internal returns (bytes32 result) {\n if (_source.length == 0) {\n return 0x0;\n }\n\n assembly {\n result := mload(add(_source, 32))\n }\n }\n\n function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) {\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n result := keccak256(add(add(_bytes, 32), _start), _length)\n }\n }\n}\n" - }, - "@keep-network/bitcoin-spv-sol/contracts/SafeMath.sol": { - "content": "pragma solidity ^0.8.4;\n\n/*\nThe MIT License (MIT)\n\nCopyright (c) 2016 Smart Contract Solutions, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n\n/**\n * @title SafeMath\n * @dev Math operations with safety checks that throw on error\n */\nlibrary SafeMath {\n\n /**\n * @dev Multiplies two numbers, throws on overflow.\n */\n function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\n // Gas optimization: this is cheaper than asserting 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\n if (_a == 0) {\n return 0;\n }\n\n c = _a * _b;\n require(c / _a == _b, \"Overflow during multiplication.\");\n return c;\n }\n\n /**\n * @dev Integer division of two numbers, truncating the quotient.\n */\n function div(uint256 _a, uint256 _b) internal pure returns (uint256) {\n // assert(_b > 0); // Solidity automatically throws when dividing by 0\n // uint256 c = _a / _b;\n // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold\n return _a / _b;\n }\n\n /**\n * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).\n */\n function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {\n require(_b <= _a, \"Underflow during subtraction.\");\n return _a - _b;\n }\n\n /**\n * @dev Adds two numbers, throws on overflow.\n */\n function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\n c = _a + _b;\n require(c >= _a, \"Overflow during addition.\");\n return c;\n }\n}\n" - }, - "@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.0;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\n\nimport \"./IBridge.sol\";\nimport \"./ITBTCVault.sol\";\n\n/// @title Abstract AbstractTBTCDepositor contract.\n/// @notice This abstract contract is meant to facilitate integration of protocols\n/// aiming to use tBTC as an underlying Bitcoin bridge.\n///\n/// Such an integrator is supposed to:\n/// - Create a child contract inheriting from this abstract contract\n/// - Call the `__AbstractTBTCDepositor_initialize` initializer function\n/// - Use the `_initializeDeposit` and `_finalizeDeposit` as part of their\n/// business logic in order to initialize and finalize deposits.\n///\n/// @dev Example usage:\n/// ```\n/// // Example upgradeable integrator contract.\n/// contract ExampleTBTCIntegrator is AbstractTBTCDepositor, Initializable {\n/// /// @custom:oz-upgrades-unsafe-allow constructor\n/// constructor() {\n/// // Prevents the contract from being initialized again.\n/// _disableInitializers();\n/// }\n///\n/// function initialize(\n/// address _bridge,\n/// address _tbtcVault\n/// ) external initializer {\n/// __AbstractTBTCDepositor_initialize(_bridge, _tbtcVault);\n/// }\n///\n/// function startProcess(\n/// IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n/// IBridgeTypes.DepositRevealInfo calldata reveal\n/// ) external {\n/// // Embed necessary context as extra data.\n/// bytes32 extraData = ...;\n///\n/// uint256 depositKey = _initializeDeposit(\n/// fundingTx,\n/// reveal,\n/// extraData\n/// );\n///\n/// // Use the depositKey to track the process.\n/// }\n///\n/// function finalizeProcess(uint256 depositKey) external {\n/// (\n/// uint256 initialDepositAmount,\n/// uint256 tbtcAmount,\n/// bytes32 extraData\n/// ) = _finalizeDeposit(depositKey);\n///\n/// // Do something with the minted TBTC using context\n/// // embedded in the extraData.\n/// }\n/// }\nabstract contract AbstractTBTCDepositor {\n using BTCUtils for bytes;\n\n /// @notice Multiplier to convert satoshi to TBTC token units.\n uint256 public constant SATOSHI_MULTIPLIER = 10**10;\n\n /// @notice Bridge contract address.\n IBridge public bridge;\n /// @notice TBTCVault contract address.\n ITBTCVault public tbtcVault;\n /// @notice Mapping holding information about pending deposits that have\n /// been initialized but not finalized yet. If the deposit is not\n /// in this mapping it means it has already been finalized or it\n /// has not been initialized yet.\n mapping(uint256 => bool) public pendingDeposits;\n\n // Reserved storage space that allows adding more variables without affecting\n // the storage layout of the child contracts. The convention from OpenZeppelin\n // suggests the storage space should add up to 50 slots. If more variables are\n // added in the upcoming versions one need to reduce the array size accordingly.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[47] private __gap;\n\n event DepositInitialized(uint256 indexed depositKey, uint32 initializedAt);\n\n event DepositFinalized(\n uint256 indexed depositKey,\n uint256 tbtcAmount,\n uint32 finalizedAt\n );\n\n /// @notice Initializes the contract. MUST BE CALLED from the child\n /// contract initializer.\n // slither-disable-next-line dead-code\n function __AbstractTBTCDepositor_initialize(\n address _bridge,\n address _tbtcVault\n ) internal {\n require(\n address(bridge) == address(0) && address(tbtcVault) == address(0),\n \"AbstractTBTCDepositor already initialized\"\n );\n\n require(_bridge != address(0), \"Bridge address cannot be zero\");\n require(_tbtcVault != address(0), \"TBTCVault address cannot be zero\");\n\n bridge = IBridge(_bridge);\n tbtcVault = ITBTCVault(_tbtcVault);\n }\n\n /// @notice Initializes a deposit by revealing it to the Bridge.\n /// @param fundingTx Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.\n /// @param reveal Deposit reveal data, see `IBridgeTypes.DepositRevealInfo` struct.\n /// @param extraData 32-byte deposit extra data.\n /// @return depositKey Deposit key computed as\n /// `keccak256(fundingTxHash | reveal.fundingOutputIndex)`. This\n /// key can be used to refer to the deposit in the Bridge and\n /// TBTCVault contracts.\n /// @dev Requirements:\n /// - The revealed vault address must match the TBTCVault address,\n /// - All requirements from {Bridge#revealDepositWithExtraData}\n /// function must be met.\n // slither-disable-next-line dead-code\n function _initializeDeposit(\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n IBridgeTypes.DepositRevealInfo calldata reveal,\n bytes32 extraData\n ) internal returns (uint256) {\n require(reveal.vault == address(tbtcVault), \"Vault address mismatch\");\n\n uint256 depositKey = _calculateDepositKey(\n _calculateBitcoinTxHash(fundingTx),\n reveal.fundingOutputIndex\n );\n\n pendingDeposits[depositKey] = true;\n\n emit DepositInitialized(\n depositKey,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp)\n );\n\n // The Bridge does not allow to reveal the same deposit twice and\n // revealed deposits stay there forever. The transaction will revert\n // if the deposit has already been revealed so, there is no need to do\n // an explicit check here.\n bridge.revealDepositWithExtraData(fundingTx, reveal, extraData);\n\n return depositKey;\n }\n\n /// @notice Finalizes a deposit by calculating the amount of TBTC minted\n /// for the deposit\n /// @param depositKey Deposit key identifying the deposit.\n /// @return initialDepositAmount Amount of funding transaction deposit. In\n /// TBTC token decimals precision.\n /// @return tbtcAmount Approximate amount of TBTC minted for the deposit. In\n /// TBTC token decimals precision.\n /// @return extraData 32-byte deposit extra data.\n /// @dev Requirements:\n /// - The deposit must be initialized but not finalized\n /// (in the context of this contract) yet.\n /// - The deposit must be finalized on the Bridge side. That means the\n /// deposit must be either swept or optimistically minted.\n /// @dev IMPORTANT NOTE: The tbtcAmount returned by this function is an\n /// approximation. See documentation of the `calculateTbtcAmount`\n /// responsible for calculating this value for more details.\n // slither-disable-next-line dead-code\n function _finalizeDeposit(uint256 depositKey)\n internal\n returns (\n uint256 initialDepositAmount,\n uint256 tbtcAmount,\n bytes32 extraData\n )\n {\n require(pendingDeposits[depositKey], \"Deposit not initialized\");\n\n IBridgeTypes.DepositRequest memory deposit = bridge.deposits(\n depositKey\n );\n (, uint64 finalizedAt) = tbtcVault.optimisticMintingRequests(\n depositKey\n );\n\n require(\n deposit.sweptAt != 0 || finalizedAt != 0,\n \"Deposit not finalized by the bridge\"\n );\n\n // We can safely delete the deposit from the pending deposits mapping.\n // This deposit cannot be initialized again because the bridge does not\n // allow to reveal the same deposit twice. Deleting the deposit from\n // the mapping will also prevent the finalizeDeposit function from\n // being called again for the same deposit.\n // slither-disable-next-line reentrancy-no-eth\n delete pendingDeposits[depositKey];\n\n initialDepositAmount = deposit.amount * SATOSHI_MULTIPLIER;\n\n tbtcAmount = _calculateTbtcAmount(deposit.amount, deposit.treasuryFee);\n\n // slither-disable-next-line reentrancy-events\n emit DepositFinalized(\n depositKey,\n tbtcAmount,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp)\n );\n\n extraData = deposit.extraData;\n }\n\n /// @notice Calculates the amount of TBTC minted for the deposit.\n /// @param depositAmountSat Deposit amount in satoshi (1e8 precision).\n /// This is the actual amount deposited by the deposit creator, i.e.\n /// the gross amount the Bridge's fees are cut from.\n /// @param depositTreasuryFeeSat Deposit treasury fee in satoshi (1e8 precision).\n /// This is an accurate value of the treasury fee that was actually\n /// cut upon minting.\n /// @return tbtcAmount Approximate amount of TBTC minted for the deposit.\n /// @dev IMPORTANT NOTE: The tbtcAmount returned by this function may\n /// not correspond to the actual amount of TBTC minted for the deposit.\n /// Although the treasury fee cut upon minting is known precisely,\n /// this is not the case for the optimistic minting fee and the Bitcoin\n /// transaction fee. To overcome that problem, this function just takes\n /// the current maximum allowed values of both fees, at the moment of deposit\n /// finalization. For the great majority of the deposits, such an\n /// algorithm will return a tbtcAmount slightly lesser than the\n /// actual amount of TBTC minted for the deposit. This will cause\n /// some TBTC to be left in the contract and ensure there is enough\n /// liquidity to finalize the deposit. However, in some rare cases,\n /// where the actual values of those fees change between the deposit\n /// minting and finalization, the tbtcAmount returned by this function\n /// may be greater than the actual amount of TBTC minted for the deposit.\n /// If this happens and the reserve coming from previous deposits\n /// leftovers does not provide enough liquidity, the deposit will have\n /// to wait for finalization until the reserve is refilled by subsequent\n /// deposits or a manual top-up. The integrator is responsible for\n /// handling such cases.\n // slither-disable-next-line dead-code\n function _calculateTbtcAmount(\n uint64 depositAmountSat,\n uint64 depositTreasuryFeeSat\n ) internal view virtual returns (uint256) {\n // Both deposit amount and treasury fee are in the 1e8 satoshi precision.\n // We need to convert them to the 1e18 TBTC precision.\n uint256 amountSubTreasury = (depositAmountSat - depositTreasuryFeeSat) *\n SATOSHI_MULTIPLIER;\n\n uint256 omFeeDivisor = tbtcVault.optimisticMintingFeeDivisor();\n uint256 omFee = omFeeDivisor > 0\n ? (amountSubTreasury / omFeeDivisor)\n : 0;\n\n // The deposit transaction max fee is in the 1e8 satoshi precision.\n // We need to convert them to the 1e18 TBTC precision.\n (, , uint64 depositTxMaxFee, ) = bridge.depositParameters();\n uint256 txMaxFee = depositTxMaxFee * SATOSHI_MULTIPLIER;\n\n return amountSubTreasury - omFee - txMaxFee;\n }\n\n /// @notice Calculates the deposit key for the given funding transaction\n /// hash and funding output index.\n /// @param fundingTxHash Funding transaction hash.\n /// @param fundingOutputIndex Funding output index.\n /// @return depositKey Deposit key computed as\n /// `keccak256(fundingTxHash | reveal.fundingOutputIndex)`. This\n /// key can be used to refer to the deposit in the Bridge and\n /// TBTCVault contracts.\n // slither-disable-next-line dead-code\n function _calculateDepositKey(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex\n ) internal pure returns (uint256) {\n return\n uint256(\n keccak256(abi.encodePacked(fundingTxHash, fundingOutputIndex))\n );\n }\n\n /// @notice Calculates the Bitcoin transaction hash for the given Bitcoin\n /// transaction data.\n /// @param txInfo Bitcoin transaction data, see `IBridgeTypes.BitcoinTxInfo` struct.\n /// @return txHash Bitcoin transaction hash.\n // slither-disable-next-line dead-code\n function _calculateBitcoinTxHash(IBridgeTypes.BitcoinTxInfo calldata txInfo)\n internal\n view\n returns (bytes32)\n {\n return\n abi\n .encodePacked(\n txInfo.version,\n txInfo.inputVector,\n txInfo.outputVector,\n txInfo.locktime\n )\n .hash256View();\n }\n}\n" - }, - "@keep-network/tbtc-v2/contracts/integrator/IBridge.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.0;\n\n/// @notice Namespace which groups all types relevant to the IBridge interface.\n/// @dev This is a mirror of the real types used in the Bridge contract.\n/// This way, the `integrator` subpackage does not need to import\n/// anything from the `bridge` subpackage and explicitly depend on it.\n/// This simplifies the dependency graph for integrators.\nlibrary IBridgeTypes {\n /// @dev See bridge/BitcoinTx.sol#Info\n struct BitcoinTxInfo {\n bytes4 version;\n bytes inputVector;\n bytes outputVector;\n bytes4 locktime;\n }\n\n /// @dev See bridge/Deposit.sol#DepositRevealInfo\n struct DepositRevealInfo {\n uint32 fundingOutputIndex;\n bytes8 blindingFactor;\n bytes20 walletPubKeyHash;\n bytes20 refundPubKeyHash;\n bytes4 refundLocktime;\n address vault;\n }\n\n /// @dev See bridge/Deposit.sol#DepositRequest\n struct DepositRequest {\n address depositor;\n uint64 amount;\n uint32 revealedAt;\n address vault;\n uint64 treasuryFee;\n uint32 sweptAt;\n bytes32 extraData;\n }\n}\n\n/// @notice Interface of the Bridge contract.\n/// @dev See bridge/Bridge.sol\ninterface IBridge {\n /// @dev See {Bridge#revealDepositWithExtraData}\n function revealDepositWithExtraData(\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n IBridgeTypes.DepositRevealInfo calldata reveal,\n bytes32 extraData\n ) external;\n\n /// @dev See {Bridge#deposits}\n function deposits(uint256 depositKey)\n external\n view\n returns (IBridgeTypes.DepositRequest memory);\n\n /// @dev See {Bridge#depositParameters}\n function depositParameters()\n external\n view\n returns (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n );\n}\n" - }, - "@keep-network/tbtc-v2/contracts/integrator/ITBTCVault.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.0;\n\n/// @notice Interface of the TBTCVault contract.\n/// @dev See vault/TBTCVault.sol\ninterface ITBTCVault {\n /// @dev See {TBTCVault#optimisticMintingRequests}\n function optimisticMintingRequests(uint256 depositKey)\n external\n returns (uint64 requestedAt, uint64 finalizedAt);\n\n /// @dev See {TBTCVault#optimisticMintingFeeDivisor}\n function optimisticMintingFeeDivisor() external view returns (uint32);\n}\n" - }, - "@keep-network/tbtc-v2/contracts/test/TestTBTCDepositor.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\n\npragma solidity ^0.8.0;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\n\nimport \"../integrator/AbstractTBTCDepositor.sol\";\nimport \"../integrator/IBridge.sol\";\nimport \"../integrator/ITBTCVault.sol\";\n\ncontract TestTBTCDepositor is AbstractTBTCDepositor {\n event InitializeDepositReturned(uint256 depositKey);\n\n event FinalizeDepositReturned(\n uint256 initialDepositAmount,\n uint256 tbtcAmount,\n bytes32 extraData\n );\n\n function initialize(address _bridge, address _tbtcVault) external {\n __AbstractTBTCDepositor_initialize(_bridge, _tbtcVault);\n }\n\n function initializeDepositPublic(\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n IBridgeTypes.DepositRevealInfo calldata reveal,\n bytes32 extraData\n ) external {\n uint256 depositKey = _initializeDeposit(fundingTx, reveal, extraData);\n emit InitializeDepositReturned(depositKey);\n }\n\n function finalizeDepositPublic(uint256 depositKey) external {\n (\n uint256 initialDepositAmount,\n uint256 tbtcAmount,\n bytes32 extraData\n ) = _finalizeDeposit(depositKey);\n emit FinalizeDepositReturned(\n initialDepositAmount,\n tbtcAmount,\n extraData\n );\n }\n\n function calculateTbtcAmountPublic(\n uint64 depositAmountSat,\n uint64 depositTreasuryFeeSat\n ) external view returns (uint256) {\n return _calculateTbtcAmount(depositAmountSat, depositTreasuryFeeSat);\n }\n}\n\ncontract MockBridge is IBridge {\n using BTCUtils for bytes;\n\n mapping(uint256 => IBridgeTypes.DepositRequest) internal _deposits;\n\n uint64 internal _depositTreasuryFeeDivisor = 50; // 1/50 == 100 bps == 2% == 0.02\n uint64 internal _depositTxMaxFee = 1000; // 1000 satoshi = 0.00001 BTC\n\n event DepositRevealed(uint256 depositKey);\n\n function revealDepositWithExtraData(\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n IBridgeTypes.DepositRevealInfo calldata reveal,\n bytes32 extraData\n ) external {\n bytes32 fundingTxHash = abi\n .encodePacked(\n fundingTx.version,\n fundingTx.inputVector,\n fundingTx.outputVector,\n fundingTx.locktime\n )\n .hash256View();\n\n uint256 depositKey = uint256(\n keccak256(\n abi.encodePacked(fundingTxHash, reveal.fundingOutputIndex)\n )\n );\n\n require(\n _deposits[depositKey].revealedAt == 0,\n \"Deposit already revealed\"\n );\n\n bytes memory fundingOutput = fundingTx\n .outputVector\n .extractOutputAtIndex(reveal.fundingOutputIndex);\n\n uint64 fundingOutputAmount = fundingOutput.extractValue();\n\n IBridgeTypes.DepositRequest memory request;\n\n request.depositor = msg.sender;\n request.amount = fundingOutputAmount;\n /* solhint-disable-next-line not-rely-on-time */\n request.revealedAt = uint32(block.timestamp);\n request.vault = reveal.vault;\n request.treasuryFee = _depositTreasuryFeeDivisor > 0\n ? fundingOutputAmount / _depositTreasuryFeeDivisor\n : 0;\n request.sweptAt = 0;\n request.extraData = extraData;\n\n _deposits[depositKey] = request;\n\n emit DepositRevealed(depositKey);\n }\n\n function sweepDeposit(uint256 depositKey) public {\n require(_deposits[depositKey].revealedAt != 0, \"Deposit not revealed\");\n require(_deposits[depositKey].sweptAt == 0, \"Deposit already swept\");\n /* solhint-disable-next-line not-rely-on-time */\n _deposits[depositKey].sweptAt = uint32(block.timestamp);\n }\n\n function deposits(uint256 depositKey)\n external\n view\n returns (IBridgeTypes.DepositRequest memory)\n {\n return _deposits[depositKey];\n }\n\n function depositParameters()\n external\n view\n returns (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n )\n {\n depositDustThreshold = 0;\n depositTreasuryFeeDivisor = 0;\n depositTxMaxFee = _depositTxMaxFee;\n depositRevealAheadPeriod = 0;\n }\n\n function setDepositTreasuryFeeDivisor(uint64 value) external {\n _depositTreasuryFeeDivisor = value;\n }\n\n function setDepositTxMaxFee(uint64 value) external {\n _depositTxMaxFee = value;\n }\n}\n\ncontract MockTBTCVault is ITBTCVault {\n struct Request {\n uint64 requestedAt;\n uint64 finalizedAt;\n }\n\n mapping(uint256 => Request) internal _requests;\n\n uint32 public optimisticMintingFeeDivisor = 100; // 1%\n\n function optimisticMintingRequests(uint256 depositKey)\n external\n returns (uint64 requestedAt, uint64 finalizedAt)\n {\n Request memory request = _requests[depositKey];\n return (request.requestedAt, request.finalizedAt);\n }\n\n function createOptimisticMintingRequest(uint256 depositKey) external {\n require(\n _requests[depositKey].requestedAt == 0,\n \"Request already exists\"\n );\n /* solhint-disable-next-line not-rely-on-time */\n _requests[depositKey].requestedAt = uint64(block.timestamp);\n }\n\n function finalizeOptimisticMintingRequest(uint256 depositKey) public {\n require(\n _requests[depositKey].requestedAt != 0,\n \"Request does not exist\"\n );\n require(\n _requests[depositKey].finalizedAt == 0,\n \"Request already finalized\"\n );\n /* solhint-disable-next-line not-rely-on-time */\n _requests[depositKey].finalizedAt = uint64(block.timestamp);\n }\n\n function setOptimisticMintingFeeDivisor(uint32 value) external {\n optimisticMintingFeeDivisor = value;\n }\n}\n" - }, - "@openzeppelin/contracts/access/Ownable.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n /**\n * @dev The caller account is not authorized to perform an operation.\n */\n error OwnableUnauthorizedAccount(address account);\n\n /**\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\n */\n error OwnableInvalidOwner(address owner);\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n */\n constructor(address initialOwner) {\n if (initialOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(initialOwner);\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n if (owner() != _msgSender()) {\n revert OwnableUnauthorizedAccount(_msgSender());\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n if (newOwner == address(0)) {\n revert OwnableInvalidOwner(address(0));\n }\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n" - }, - "@openzeppelin/contracts/interfaces/draft-IERC6093.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard ERC20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.\n */\ninterface IERC20Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC20InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC20InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n * @param allowance Amount of tokens a `spender` is allowed to operate with.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC20InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.\n */\ninterface IERC721Errors {\n /**\n * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.\n * Used in balance queries.\n * @param owner Address of the current owner of a token.\n */\n error ERC721InvalidOwner(address owner);\n\n /**\n * @dev Indicates a `tokenId` whose `owner` is the zero address.\n * @param tokenId Identifier number of a token.\n */\n error ERC721NonexistentToken(uint256 tokenId);\n\n /**\n * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param tokenId Identifier number of a token.\n * @param owner Address of the current owner of a token.\n */\n error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC721InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC721InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param tokenId Identifier number of a token.\n */\n error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC721InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.\n */\ninterface IERC1155Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n * @param tokenId Identifier number of a token.\n */\n error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC1155InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC1155InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param owner Address of the current owner of a token.\n */\n error ERC1155MissingApprovalForAll(address operator, address owner);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC1155InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC1155InvalidOperator(address operator);\n\n /**\n * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n * Used in batch transfers.\n * @param idsLength Length of the array of token identifiers\n * @param valuesLength Length of the array of token amounts\n */\n error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n" - }, - "@openzeppelin/contracts/interfaces/IERC4626.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"../token/ERC20/extensions/IERC20Metadata.sol\";\n\n/**\n * @dev Interface of the ERC4626 \"Tokenized Vault Standard\", as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\n */\ninterface IERC4626 is IERC20, IERC20Metadata {\n event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed sender,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /**\n * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\n *\n * - MUST be an ERC-20 token contract.\n * - MUST NOT revert.\n */\n function asset() external view returns (address assetTokenAddress);\n\n /**\n * @dev Returns the total amount of the underlying asset that is “managed” by Vault.\n *\n * - SHOULD include any compounding that occurs from yield.\n * - MUST be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT revert.\n */\n function totalAssets() external view returns (uint256 totalManagedAssets);\n\n /**\n * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\n * scenario where all the conditions are met.\n *\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT show any variations depending on the caller.\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n * - MUST NOT revert.\n *\n * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n * from.\n */\n function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\n * scenario where all the conditions are met.\n *\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT show any variations depending on the caller.\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n * - MUST NOT revert.\n *\n * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n * from.\n */\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\n * through a deposit call.\n *\n * - MUST return a limited value if receiver is subject to some deposit limit.\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\n * - MUST NOT revert.\n */\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\n * current on-chain conditions.\n *\n * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\n * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\n * in the same transaction.\n * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\n * deposit would be accepted, regardless if the user has enough tokens approved, etc.\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n */\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\n *\n * - MUST emit the Deposit event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * deposit execution, and are accounted for during deposit.\n * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\n * approving enough underlying tokens to the Vault contract, etc).\n *\n * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n */\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n /**\n * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\n * - MUST return a limited value if receiver is subject to some mint limit.\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\n * - MUST NOT revert.\n */\n function maxMint(address receiver) external view returns (uint256 maxShares);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\n * current on-chain conditions.\n *\n * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\n * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\n * same transaction.\n * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\n * would be accepted, regardless if the user has enough tokens approved, etc.\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by minting.\n */\n function previewMint(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\n *\n * - MUST emit the Deposit event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\n * execution, and are accounted for during mint.\n * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\n * approving enough underlying tokens to the Vault contract, etc).\n *\n * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n */\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n /**\n * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\n * Vault, through a withdraw call.\n *\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n * - MUST NOT revert.\n */\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\n * given current on-chain conditions.\n *\n * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\n * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\n * called\n * in the same transaction.\n * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\n * the withdrawal would be accepted, regardless if the user has enough shares, etc.\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n */\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\n *\n * - MUST emit the Withdraw event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * withdraw execution, and are accounted for during withdraw.\n * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\n * not having enough shares, etc).\n *\n * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n * Those methods should be performed separately.\n */\n function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\n\n /**\n * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\n * through a redeem call.\n *\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\n * - MUST NOT revert.\n */\n function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\n * given current on-chain conditions.\n *\n * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\n * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\n * same transaction.\n * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\n * redemption would be accepted, regardless if the user has enough shares, etc.\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\n */\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\n *\n * - MUST emit the Withdraw event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * redeem execution, and are accounted for during redeem.\n * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\n * not having enough shares, etc).\n *\n * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n * Those methods should be performed separately.\n */\n function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/ERC20.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC20Metadata} from \"./extensions/IERC20Metadata.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {IERC20Errors} from \"../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n */\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\n mapping(address account => uint256) private _balances;\n\n mapping(address account => mapping(address spender => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the default value returned by this function, unless\n * it's overridden.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `value`.\n */\n function transfer(address to, uint256 value) public virtual returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, value);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 value) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, value);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `value`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `value`.\n */\n function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, value);\n _transfer(from, to, value);\n return true;\n }\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead.\n */\n function _transfer(address from, address to, uint256 value) internal {\n if (from == address(0)) {\n revert ERC20InvalidSender(address(0));\n }\n if (to == address(0)) {\n revert ERC20InvalidReceiver(address(0));\n }\n _update(from, to, value);\n }\n\n /**\n * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n * this function.\n *\n * Emits a {Transfer} event.\n */\n function _update(address from, address to, uint256 value) internal virtual {\n if (from == address(0)) {\n // Overflow check required: The rest of the code assumes that totalSupply never overflows\n _totalSupply += value;\n } else {\n uint256 fromBalance = _balances[from];\n if (fromBalance < value) {\n revert ERC20InsufficientBalance(from, fromBalance, value);\n }\n unchecked {\n // Overflow not possible: value <= fromBalance <= totalSupply.\n _balances[from] = fromBalance - value;\n }\n }\n\n if (to == address(0)) {\n unchecked {\n // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\n _totalSupply -= value;\n }\n } else {\n unchecked {\n // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n _balances[to] += value;\n }\n }\n\n emit Transfer(from, to, value);\n }\n\n /**\n * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n * Relies on the `_update` mechanism\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead.\n */\n function _mint(address account, uint256 value) internal {\n if (account == address(0)) {\n revert ERC20InvalidReceiver(address(0));\n }\n _update(address(0), account, value);\n }\n\n /**\n * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n * Relies on the `_update` mechanism.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead\n */\n function _burn(address account, uint256 value) internal {\n if (account == address(0)) {\n revert ERC20InvalidSender(address(0));\n }\n _update(account, address(0), value);\n }\n\n /**\n * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n *\n * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n */\n function _approve(address owner, address spender, uint256 value) internal {\n _approve(owner, spender, value, true);\n }\n\n /**\n * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n *\n * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\n * `Approval` event during `transferFrom` operations.\n *\n * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\n * true using the following override:\n * ```\n * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n * super._approve(owner, spender, value, true);\n * }\n * ```\n *\n * Requirements are the same as {_approve}.\n */\n function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n if (owner == address(0)) {\n revert ERC20InvalidApprover(address(0));\n }\n if (spender == address(0)) {\n revert ERC20InvalidSpender(address(0));\n }\n _allowances[owner][spender] = value;\n if (emitEvent) {\n emit Approval(owner, spender, value);\n }\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `value`.\n *\n * Does not update the allowance value in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Does not emit an {Approval} event.\n */\n function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n if (currentAllowance < value) {\n revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n }\n unchecked {\n _approve(owner, spender, currentAllowance - value, false);\n }\n }\n }\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20, IERC20Metadata, ERC20} from \"../ERC20.sol\";\nimport {SafeERC20} from \"../utils/SafeERC20.sol\";\nimport {IERC4626} from \"../../../interfaces/IERC4626.sol\";\nimport {Math} from \"../../../utils/math/Math.sol\";\n\n/**\n * @dev Implementation of the ERC4626 \"Tokenized Vault Standard\" as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].\n *\n * This extension allows the minting and burning of \"shares\" (represented using the ERC20 inheritance) in exchange for\n * underlying \"assets\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\n * the ERC20 standard. Any additional extensions included along it would affect the \"shares\" token represented by this\n * contract and not the \"assets\" token which is an independent contract.\n *\n * [CAUTION]\n * ====\n * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning\n * with a \"donation\" to the vault that inflates the price of a share. This is variously known as a donation or inflation\n * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial\n * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may\n * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by\n * verifying the amount received is as expected, using a wrapper that performs these checks such as\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\n *\n * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`\n * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault\n * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself\n * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset\n * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's\n * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more\n * expensive than it is profitable. More details about the underlying math can be found\n * xref:erc4626.adoc#inflation-attack[here].\n *\n * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued\n * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets\n * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience\n * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the\n * `_convertToShares` and `_convertToAssets` functions.\n *\n * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].\n * ====\n */\nabstract contract ERC4626 is ERC20, IERC4626 {\n using Math for uint256;\n\n IERC20 private immutable _asset;\n uint8 private immutable _underlyingDecimals;\n\n /**\n * @dev Attempted to deposit more assets than the max amount for `receiver`.\n */\n error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);\n\n /**\n * @dev Attempted to mint more shares than the max amount for `receiver`.\n */\n error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);\n\n /**\n * @dev Attempted to withdraw more assets than the max amount for `receiver`.\n */\n error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);\n\n /**\n * @dev Attempted to redeem more shares than the max amount for `receiver`.\n */\n error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);\n\n /**\n * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).\n */\n constructor(IERC20 asset_) {\n (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\n _underlyingDecimals = success ? assetDecimals : 18;\n _asset = asset_;\n }\n\n /**\n * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\n */\n function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {\n (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(\n abi.encodeCall(IERC20Metadata.decimals, ())\n );\n if (success && encodedDecimals.length >= 32) {\n uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));\n if (returnedDecimals <= type(uint8).max) {\n return (true, uint8(returnedDecimals));\n }\n }\n return (false, 0);\n }\n\n /**\n * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This\n * \"original\" value is cached during construction of the vault contract. If this read operation fails (e.g., the\n * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.\n *\n * See {IERC20Metadata-decimals}.\n */\n function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {\n return _underlyingDecimals + _decimalsOffset();\n }\n\n /** @dev See {IERC4626-asset}. */\n function asset() public view virtual returns (address) {\n return address(_asset);\n }\n\n /** @dev See {IERC4626-totalAssets}. */\n function totalAssets() public view virtual returns (uint256) {\n return _asset.balanceOf(address(this));\n }\n\n /** @dev See {IERC4626-convertToShares}. */\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n return _convertToShares(assets, Math.Rounding.Floor);\n }\n\n /** @dev See {IERC4626-convertToAssets}. */\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n return _convertToAssets(shares, Math.Rounding.Floor);\n }\n\n /** @dev See {IERC4626-maxDeposit}. */\n function maxDeposit(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n /** @dev See {IERC4626-maxMint}. */\n function maxMint(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n /** @dev See {IERC4626-maxWithdraw}. */\n function maxWithdraw(address owner) public view virtual returns (uint256) {\n return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);\n }\n\n /** @dev See {IERC4626-maxRedeem}. */\n function maxRedeem(address owner) public view virtual returns (uint256) {\n return balanceOf(owner);\n }\n\n /** @dev See {IERC4626-previewDeposit}. */\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n return _convertToShares(assets, Math.Rounding.Floor);\n }\n\n /** @dev See {IERC4626-previewMint}. */\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n return _convertToAssets(shares, Math.Rounding.Ceil);\n }\n\n /** @dev See {IERC4626-previewWithdraw}. */\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n return _convertToShares(assets, Math.Rounding.Ceil);\n }\n\n /** @dev See {IERC4626-previewRedeem}. */\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n return _convertToAssets(shares, Math.Rounding.Floor);\n }\n\n /** @dev See {IERC4626-deposit}. */\n function deposit(uint256 assets, address receiver) public virtual returns (uint256) {\n uint256 maxAssets = maxDeposit(receiver);\n if (assets > maxAssets) {\n revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);\n }\n\n uint256 shares = previewDeposit(assets);\n _deposit(_msgSender(), receiver, assets, shares);\n\n return shares;\n }\n\n /** @dev See {IERC4626-mint}.\n *\n * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.\n * In this case, the shares will be minted without requiring any assets to be deposited.\n */\n function mint(uint256 shares, address receiver) public virtual returns (uint256) {\n uint256 maxShares = maxMint(receiver);\n if (shares > maxShares) {\n revert ERC4626ExceededMaxMint(receiver, shares, maxShares);\n }\n\n uint256 assets = previewMint(shares);\n _deposit(_msgSender(), receiver, assets, shares);\n\n return assets;\n }\n\n /** @dev See {IERC4626-withdraw}. */\n function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {\n uint256 maxAssets = maxWithdraw(owner);\n if (assets > maxAssets) {\n revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);\n }\n\n uint256 shares = previewWithdraw(assets);\n _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n return shares;\n }\n\n /** @dev See {IERC4626-redeem}. */\n function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {\n uint256 maxShares = maxRedeem(owner);\n if (shares > maxShares) {\n revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);\n }\n\n uint256 assets = previewRedeem(shares);\n _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n return assets;\n }\n\n /**\n * @dev Internal conversion function (from assets to shares) with support for rounding direction.\n */\n function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {\n return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);\n }\n\n /**\n * @dev Internal conversion function (from shares to assets) with support for rounding direction.\n */\n function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {\n return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);\n }\n\n /**\n * @dev Deposit/mint common workflow.\n */\n function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {\n // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the\n // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\n // calls the vault, which is assumed not malicious.\n //\n // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\n // assets are transferred and before the shares are minted, which is a valid state.\n // slither-disable-next-line reentrancy-no-eth\n SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);\n _mint(receiver, shares);\n\n emit Deposit(caller, receiver, assets, shares);\n }\n\n /**\n * @dev Withdraw/redeem common workflow.\n */\n function _withdraw(\n address caller,\n address receiver,\n address owner,\n uint256 assets,\n uint256 shares\n ) internal virtual {\n if (caller != owner) {\n _spendAllowance(owner, caller, shares);\n }\n\n // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\n // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\n // calls the vault, which is assumed not malicious.\n //\n // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\n // shares are burned and after the assets are transferred, which is a valid state.\n _burn(owner, shares);\n SafeERC20.safeTransfer(_asset, receiver, assets);\n\n emit Withdraw(caller, receiver, owner, assets, shares);\n }\n\n function _decimalsOffset() internal view virtual returns (uint8) {\n return 0;\n }\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n * doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n * token.safeTransferFrom(msg.sender, address(this), value);\n * ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n *\n * CAUTION: See Security Considerations above.\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/IERC20.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the value of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the value of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 value) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n * caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 value) external returns (bool);\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\n * allowance mechanism. `value` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n" - }, - "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC20Permit} from \"../extensions/IERC20Permit.sol\";\nimport {Address} from \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n /**\n * @dev An operation with an ERC20 token failed.\n */\n error SafeERC20FailedOperation(address token);\n\n /**\n * @dev Indicates a failed `decreaseAllowance` request.\n */\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n forceApprove(token, spender, oldAllowance + value);\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n * value, non-reverting calls are assumed to be successful.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n unchecked {\n uint256 currentAllowance = token.allowance(address(this), spender);\n if (currentAllowance < requestedDecrease) {\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n }\n forceApprove(token, spender, currentAllowance - requestedDecrease);\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n _callOptionalReturn(token, approvalCall);\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data);\n if (returndata.length != 0 && !abi.decode(returndata, (bool))) {\n revert SafeERC20FailedOperation(address(token));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n // and not revert is the subcall reverts.\n\n (bool success, bytes memory returndata) = address(token).call(data);\n return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;\n }\n}\n" - }, - "@openzeppelin/contracts/utils/Address.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev The ETH balance of the account is not enough to perform the operation.\n */\n error AddressInsufficientBalance(address account);\n\n /**\n * @dev There's no code at `target` (it is not a contract).\n */\n error AddressEmptyCode(address target);\n\n /**\n * @dev A call to an address target failed. The target may have reverted.\n */\n error FailedInnerCall();\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n if (address(this).balance < amount) {\n revert AddressInsufficientBalance(address(this));\n }\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n if (!success) {\n revert FailedInnerCall();\n }\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason or custom error, it is bubbled\n * up by this function (like regular Solidity function calls). However, if\n * the call reverted with no returned reason, this function reverts with a\n * {FailedInnerCall} error.\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n if (address(this).balance < value) {\n revert AddressInsufficientBalance(address(this));\n }\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n * unsuccessful call.\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata\n ) internal view returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n if (returndata.length == 0 && target.code.length == 0) {\n revert AddressEmptyCode(target);\n }\n return returndata;\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n * revert reason or with a default {FailedInnerCall} error.\n */\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n if (!success) {\n _revert(returndata);\n } else {\n return returndata;\n }\n }\n\n /**\n * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n */\n function _revert(bytes memory returndata) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert FailedInnerCall();\n }\n }\n}\n" - }, - "@openzeppelin/contracts/utils/Context.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n" - }, - "@openzeppelin/contracts/utils/math/Math.sol": { - "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Muldiv operation overflow.\n */\n error MathOverflowedMulDiv();\n\n enum Rounding {\n Floor, // Toward negative infinity\n Ceil, // Toward positive infinity\n Trunc, // Toward zero\n Expand // Away from zero\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds towards infinity instead\n * of rounding towards zero.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n if (b == 0) {\n // Guarantee the same behavior as in a regular Solidity division.\n return a / b;\n }\n\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n * denominator == 0.\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n * Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0 = x * y; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n if (denominator <= prod1) {\n revert MathOverflowedMulDiv();\n }\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n uint256 twos = denominator & (0 - denominator);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n // works in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n * towards zero.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256 of a positive value rounded towards zero.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n */\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n return uint8(rounding) % 2 == 1;\n }\n}\n" - }, - "contracts/Dispatcher.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\nimport \"./Router.sol\";\nimport \"./stBTC.sol\";\n\n/// @title Dispatcher\n/// @notice Dispatcher is a contract that routes tBTC from stBTC to\n/// yield vaults and back. Vaults supply yield strategies with tBTC that\n/// generate yield for Bitcoin holders.\ncontract Dispatcher is Router, Ownable {\n using SafeERC20 for IERC20;\n\n /// Struct holds information about a vault.\n struct VaultInfo {\n bool authorized;\n }\n\n /// The main stBTC contract holding tBTC deposited by stakers.\n stBTC public immutable stbtc;\n /// tBTC token contract.\n IERC20 public immutable tbtc;\n /// Address of the maintainer bot.\n address public maintainer;\n\n /// Authorized Yield Vaults that implement ERC4626 standard. These\n /// vaults deposit assets to yield strategies, e.g. Uniswap V3\n /// WBTC/TBTC pool. Vault can be a part of Acre ecosystem or can be\n /// implemented externally. As long as it complies with ERC4626\n /// standard and is authorized by the owner it can be plugged into\n /// Acre.\n address[] public vaults;\n /// Mapping of vaults to their information.\n mapping(address => VaultInfo) public vaultsInfo;\n\n /// Emitted when a vault is authorized.\n /// @param vault Address of the vault.\n event VaultAuthorized(address indexed vault);\n\n /// Emitted when a vault is deauthorized.\n /// @param vault Address of the vault.\n event VaultDeauthorized(address indexed vault);\n\n /// Emitted when tBTC is routed to a vault.\n /// @param vault Address of the vault.\n /// @param amount Amount of tBTC.\n /// @param sharesOut Amount of received shares.\n event DepositAllocated(\n address indexed vault,\n uint256 amount,\n uint256 sharesOut\n );\n\n /// Emitted when the maintainer address is updated.\n /// @param maintainer Address of the new maintainer.\n event MaintainerUpdated(address indexed maintainer);\n\n /// Reverts if the vault is already authorized.\n error VaultAlreadyAuthorized();\n\n /// Reverts if the vault is not authorized.\n error VaultUnauthorized();\n\n /// Reverts if the caller is not the maintainer.\n error NotMaintainer();\n\n /// Reverts if the address is zero.\n error ZeroAddress();\n\n /// Modifier that reverts if the caller is not the maintainer.\n modifier onlyMaintainer() {\n if (msg.sender != maintainer) {\n revert NotMaintainer();\n }\n _;\n }\n\n constructor(stBTC _stbtc, IERC20 _tbtc) Ownable(msg.sender) {\n stbtc = _stbtc;\n tbtc = _tbtc;\n }\n\n /// @notice Adds a vault to the list of authorized vaults.\n /// @param vault Address of the vault to add.\n function authorizeVault(address vault) external onlyOwner {\n if (isVaultAuthorized(vault)) {\n revert VaultAlreadyAuthorized();\n }\n\n vaults.push(vault);\n vaultsInfo[vault].authorized = true;\n\n emit VaultAuthorized(vault);\n }\n\n /// @notice Removes a vault from the list of authorized vaults.\n /// @param vault Address of the vault to remove.\n function deauthorizeVault(address vault) external onlyOwner {\n if (!isVaultAuthorized(vault)) {\n revert VaultUnauthorized();\n }\n\n vaultsInfo[vault].authorized = false;\n\n for (uint256 i = 0; i < vaults.length; i++) {\n if (vaults[i] == vault) {\n vaults[i] = vaults[vaults.length - 1];\n // slither-disable-next-line costly-loop\n vaults.pop();\n break;\n }\n }\n\n emit VaultDeauthorized(vault);\n }\n\n /// @notice Updates the maintainer address.\n /// @param newMaintainer Address of the new maintainer.\n function updateMaintainer(address newMaintainer) external onlyOwner {\n if (newMaintainer == address(0)) {\n revert ZeroAddress();\n }\n\n maintainer = newMaintainer;\n\n emit MaintainerUpdated(maintainer);\n }\n\n /// TODO: make this function internal once the allocation distribution is\n /// implemented\n /// @notice Routes tBTC from stBTC to a vault. Can be called by the maintainer\n /// only.\n /// @param vault Address of the vault to route the assets to.\n /// @param amount Amount of tBTC to deposit.\n /// @param minSharesOut Minimum amount of shares to receive.\n function depositToVault(\n address vault,\n uint256 amount,\n uint256 minSharesOut\n ) public onlyMaintainer {\n if (!isVaultAuthorized(vault)) {\n revert VaultUnauthorized();\n }\n\n // slither-disable-next-line arbitrary-send-erc20\n tbtc.safeTransferFrom(address(stbtc), address(this), amount);\n tbtc.forceApprove(address(vault), amount);\n\n uint256 sharesOut = deposit(\n IERC4626(vault),\n address(stbtc),\n amount,\n minSharesOut\n );\n // slither-disable-next-line reentrancy-events\n emit DepositAllocated(vault, amount, sharesOut);\n }\n\n /// @notice Returns the list of authorized vaults.\n function getVaults() public view returns (address[] memory) {\n return vaults;\n }\n\n /// @notice Returns true if the vault is authorized.\n /// @param vault Address of the vault to check.\n function isVaultAuthorized(address vault) public view returns (bool) {\n return vaultsInfo[vault].authorized;\n }\n\n /// TODO: implement redeem() / withdraw() functions\n}\n" - }, - "contracts/lib/ERC4626Fees.sol": { - "content": "// SPDX-License-Identifier: MIT\n\n// Inspired by https://docs.openzeppelin.com/contracts/5.x/erc4626#fees\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {ERC4626} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\n\n/// @dev ERC4626 vault with entry/exit fees expressed in https://en.wikipedia.org/wiki/Basis_point[basis point (bp)].\nabstract contract ERC4626Fees is ERC4626 {\n using Math for uint256;\n\n uint256 private constant _BASIS_POINT_SCALE = 1e4;\n\n // === Overrides ===\n\n /// @dev Preview taking an entry fee on deposit. See {IERC4626-previewDeposit}.\n function previewDeposit(\n uint256 assets\n ) public view virtual override returns (uint256) {\n uint256 fee = _feeOnTotal(assets, _entryFeeBasisPoints());\n return super.previewDeposit(assets - fee);\n }\n\n /// @dev Preview adding an entry fee on mint. See {IERC4626-previewMint}.\n function previewMint(\n uint256 shares\n ) public view virtual override returns (uint256) {\n uint256 assets = super.previewMint(shares);\n return assets + _feeOnRaw(assets, _entryFeeBasisPoints());\n }\n\n // TODO: add previewWithraw\n\n // TODO: add previewRedeem\n\n /// @dev Send entry fee to {_feeRecipient}. See {IERC4626-_deposit}.\n function _deposit(\n address caller,\n address receiver,\n uint256 assets,\n uint256 shares\n ) internal virtual override {\n uint256 fee = _feeOnTotal(assets, _entryFeeBasisPoints());\n address recipient = _feeRecipient();\n\n super._deposit(caller, receiver, assets, shares);\n\n if (fee > 0 && recipient != address(this)) {\n SafeERC20.safeTransfer(IERC20(asset()), recipient, fee);\n }\n }\n\n // TODO: add withdraw\n\n // === Fee configuration ===\n\n // slither-disable-next-line dead-code\n function _entryFeeBasisPoints() internal view virtual returns (uint256);\n\n // TODO: add exitFeeBasisPoints\n\n // slither-disable-next-line dead-code\n function _feeRecipient() internal view virtual returns (address);\n\n // === Fee operations ===\n\n /// @dev Calculates the fees that should be added to an amount `assets`\n /// that does not already include fees.\n /// Used in {IERC4626-mint} and {IERC4626-withdraw} operations.\n function _feeOnRaw(\n uint256 assets,\n uint256 feeBasisPoints\n ) private pure returns (uint256) {\n return\n assets.mulDiv(\n feeBasisPoints,\n _BASIS_POINT_SCALE,\n Math.Rounding.Ceil\n );\n }\n\n /// @dev Calculates the fee part of an amount `assets` that already includes fees.\n /// Used in {IERC4626-deposit} and {IERC4626-redeem} operations.\n function _feeOnTotal(\n uint256 assets,\n uint256 feeBasisPoints\n ) private pure returns (uint256) {\n return\n assets.mulDiv(\n feeBasisPoints,\n feeBasisPoints + _BASIS_POINT_SCALE,\n Math.Rounding.Ceil\n );\n }\n}\n" - }, - "contracts/Router.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\n\n/// @title Router\n/// @notice Router is a contract that routes tBTC from stBTC to\n/// a given vault and back. Vaults supply yield strategies with tBTC that\n/// generate yield for Bitcoin holders.\nabstract contract Router {\n /// Thrown when amount of shares received is below the min set by caller.\n /// @param vault Address of the vault.\n /// @param sharesOut Amount of received shares.\n /// @param minSharesOut Minimum amount of shares expected to receive.\n error MinSharesError(\n address vault,\n uint256 sharesOut,\n uint256 minSharesOut\n );\n\n /// @notice Routes funds from stBTC to a vault. The amount of tBTC to\n /// Shares of deposited tBTC are minted to the stBTC contract.\n /// @param vault Address of the vault to route the funds to.\n /// @param receiver Address of the receiver of the shares.\n /// @param amount Amount of tBTC to deposit.\n /// @param minSharesOut Minimum amount of shares to receive.\n function deposit(\n IERC4626 vault,\n address receiver,\n uint256 amount,\n uint256 minSharesOut\n ) internal returns (uint256 sharesOut) {\n if ((sharesOut = vault.deposit(amount, receiver)) < minSharesOut) {\n revert MinSharesError(address(vault), sharesOut, minSharesOut);\n }\n }\n}\n" - }, - "contracts/stBTC.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"./Dispatcher.sol\";\nimport \"./lib/ERC4626Fees.sol\";\n\n/// @title stBTC\n/// @notice This contract implements the ERC-4626 tokenized vault standard. By\n/// staking tBTC, users acquire a liquid staking token called stBTC,\n/// commonly referred to as \"shares\". The staked tBTC is securely\n/// deposited into Acre's vaults, where it generates yield over time.\n/// Users have the flexibility to redeem stBTC, enabling them to\n/// withdraw their staked tBTC along with the accrued yield.\n/// @dev ERC-4626 is a standard to optimize and unify the technical parameters\n/// of yield-bearing vaults. This contract facilitates the minting and\n/// burning of shares (stBTC), which are represented as standard ERC20\n/// tokens, providing a seamless exchange with tBTC tokens.\ncontract stBTC is ERC4626Fees, Ownable {\n using SafeERC20 for IERC20;\n\n /// Dispatcher contract that routes tBTC from stBTC to a given vault and back.\n Dispatcher public dispatcher;\n\n /// Address of the treasury wallet, where fees should be transferred to.\n address public treasury;\n\n /// Entry fee basis points applied to entry fee calculation.\n uint256 public entryFeeBasisPoints;\n\n /// Minimum amount for a single deposit operation. The value should be set\n /// low enough so the deposits routed through TbtcDepositor contract won't\n /// be rejected. It means that minimumDepositAmount should be lower than\n /// tBTC protocol's depositDustThreshold reduced by all the minting fees taken\n /// before depositing in the Acre contract.\n uint256 public minimumDepositAmount;\n\n /// Maximum total amount of tBTC token held by Acre protocol.\n uint256 public maximumTotalAssets;\n\n /// Emitted when a referral is used.\n /// @param referral Used for referral program.\n /// @param assets Amount of tBTC tokens staked.\n event StakeReferral(uint16 indexed referral, uint256 assets);\n\n /// Emitted when the treasury wallet address is updated.\n /// @param treasury New treasury wallet address.\n event TreasuryUpdated(address treasury);\n\n /// Emitted when deposit parameters are updated.\n /// @param minimumDepositAmount New value of the minimum deposit amount.\n /// @param maximumTotalAssets New value of the maximum total assets amount.\n event DepositParametersUpdated(\n uint256 minimumDepositAmount,\n uint256 maximumTotalAssets\n );\n\n /// Emitted when the dispatcher contract is updated.\n /// @param oldDispatcher Address of the old dispatcher contract.\n /// @param newDispatcher Address of the new dispatcher contract.\n event DispatcherUpdated(address oldDispatcher, address newDispatcher);\n\n /// Emitted when the entry fee basis points are updated.\n /// @param entryFeeBasisPoints New value of the fee basis points.\n event EntryFeeBasisPointsUpdated(uint256 entryFeeBasisPoints);\n\n /// Reverts if the amount is less than the minimum deposit amount.\n /// @param amount Amount to check.\n /// @param min Minimum amount to check 'amount' against.\n error LessThanMinDeposit(uint256 amount, uint256 min);\n\n /// Reverts if the address is zero.\n error ZeroAddress();\n\n /// Reverts if the address is disallowed.\n error DisallowedAddress();\n\n constructor(\n IERC20 _tbtc,\n address _treasury\n ) ERC4626(_tbtc) ERC20(\"Acre Staked Bitcoin\", \"stBTC\") Ownable(msg.sender) {\n if (address(_treasury) == address(0)) {\n revert ZeroAddress();\n }\n treasury = _treasury;\n // TODO: Revisit the exact values closer to the launch.\n minimumDepositAmount = 0.001 * 1e18; // 0.001 tBTC\n maximumTotalAssets = 25 * 1e18; // 25 tBTC\n entryFeeBasisPoints = 5; // 5bps == 0.05% == 0.0005\n }\n\n /// @notice Updates treasury wallet address.\n /// @param newTreasury New treasury wallet address.\n function updateTreasury(address newTreasury) external onlyOwner {\n // TODO: Introduce a parameters update process.\n if (newTreasury == address(0)) {\n revert ZeroAddress();\n }\n if (newTreasury == address(this)) {\n revert DisallowedAddress();\n }\n treasury = newTreasury;\n\n emit TreasuryUpdated(newTreasury);\n }\n\n /// @notice Updates deposit parameters.\n /// @dev To disable the limit for deposits, set the maximum total assets to\n /// maximum (`type(uint256).max`).\n /// @param _minimumDepositAmount New value of the minimum deposit amount. It\n /// is the minimum amount for a single deposit operation.\n /// @param _maximumTotalAssets New value of the maximum total assets amount.\n /// It is the maximum amount of the tBTC token that the Acre protocol\n /// can hold.\n function updateDepositParameters(\n uint256 _minimumDepositAmount,\n uint256 _maximumTotalAssets\n ) external onlyOwner {\n // TODO: Introduce a parameters update process.\n minimumDepositAmount = _minimumDepositAmount;\n maximumTotalAssets = _maximumTotalAssets;\n\n emit DepositParametersUpdated(\n _minimumDepositAmount,\n _maximumTotalAssets\n );\n }\n\n // TODO: Implement a governed upgrade process that initiates an update and\n // then finalizes it after a delay.\n /// @notice Updates the dispatcher contract and gives it an unlimited\n /// allowance to transfer staked tBTC.\n /// @param newDispatcher Address of the new dispatcher contract.\n function updateDispatcher(Dispatcher newDispatcher) external onlyOwner {\n if (address(newDispatcher) == address(0)) {\n revert ZeroAddress();\n }\n\n address oldDispatcher = address(dispatcher);\n\n emit DispatcherUpdated(oldDispatcher, address(newDispatcher));\n dispatcher = newDispatcher;\n\n // TODO: Once withdrawal/rebalancing is implemented, we need to revoke the\n // approval of the vaults share tokens from the old dispatcher and approve\n // a new dispatcher to manage the share tokens.\n\n if (oldDispatcher != address(0)) {\n // Setting allowance to zero for the old dispatcher\n IERC20(asset()).forceApprove(oldDispatcher, 0);\n }\n\n // Setting allowance to max for the new dispatcher\n IERC20(asset()).forceApprove(address(dispatcher), type(uint256).max);\n }\n\n // TODO: Implement a governed upgrade process that initiates an update and\n // then finalizes it after a delay.\n /// @notice Update the entry fee basis points.\n /// @param newEntryFeeBasisPoints New value of the fee basis points.\n function updateEntryFeeBasisPoints(\n uint256 newEntryFeeBasisPoints\n ) external onlyOwner {\n entryFeeBasisPoints = newEntryFeeBasisPoints;\n\n emit EntryFeeBasisPointsUpdated(newEntryFeeBasisPoints);\n }\n\n /// @notice Mints shares to receiver by depositing exactly amount of\n /// tBTC tokens.\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\n /// which determines the minimum amount for a single deposit operation.\n /// The amount of the assets has to be pre-approved in the tBTC\n /// contract.\n /// @param assets Approved amount of tBTC tokens to deposit. This includes\n /// treasury fees for staking tBTC.\n /// @param receiver The address to which the shares will be minted.\n /// @return Minted shares adjusted for the fees taken by the treasury.\n function deposit(\n uint256 assets,\n address receiver\n ) public override returns (uint256) {\n if (assets < minimumDepositAmount) {\n revert LessThanMinDeposit(assets, minimumDepositAmount);\n }\n\n return super.deposit(assets, receiver);\n }\n\n /// @notice Mints shares to receiver by depositing tBTC tokens.\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\n /// which determines the minimum amount for a single deposit operation.\n /// The amount of the assets has to be pre-approved in the tBTC\n /// contract.\n /// The msg.sender is required to grant approval for the transfer of a\n /// certain amount of tBTC, and in addition, approval for the associated\n /// fee. Specifically, the total amount to be approved (amountToApprove)\n /// should be equal to the sum of the deposited amount and the fee.\n /// To determine the total assets amount necessary for approval\n /// corresponding to a given share amount, use the `previewMint` function.\n /// @param shares Amount of shares to mint.\n /// @param receiver The address to which the shares will be minted.\n function mint(\n uint256 shares,\n address receiver\n ) public override returns (uint256 assets) {\n if ((assets = super.mint(shares, receiver)) < minimumDepositAmount) {\n revert LessThanMinDeposit(assets, minimumDepositAmount);\n }\n }\n\n /// @notice Stakes a given amount of tBTC token and mints shares to a\n /// receiver.\n /// @dev This function calls `deposit` function from `ERC4626` contract. The\n /// amount of the assets has to be pre-approved in the tBTC contract.\n /// @param assets Approved amount for the transfer and stake.\n /// @param receiver The address to which the shares will be minted.\n /// @param referral Data used for referral program.\n /// @return shares Minted shares.\n function stake(\n uint256 assets,\n address receiver,\n uint16 referral\n ) public returns (uint256) {\n // TODO: revisit the type of referral.\n uint256 shares = deposit(assets, receiver);\n\n if (referral > 0) {\n emit StakeReferral(referral, assets);\n }\n\n return shares;\n }\n\n /// @notice Returns the maximum amount of the tBTC token that can be\n /// deposited into the vault for the receiver through a deposit\n /// call. It takes into account the deposit parameter, maximum total\n /// assets, which determines the total amount of tBTC token held by\n /// Acre. This function always returns available limit for deposits,\n /// but the fee is not taken into account. As a result of this, there\n /// always will be some dust left. If the dust is lower than the\n /// minimum deposit amount, this function will return 0.\n /// @return The maximum amount of tBTC token that can be deposited into\n /// Acre protocol for the receiver.\n function maxDeposit(address) public view override returns (uint256) {\n if (maximumTotalAssets == type(uint256).max) {\n return type(uint256).max;\n }\n\n uint256 currentTotalAssets = totalAssets();\n if (currentTotalAssets >= maximumTotalAssets) return 0;\n\n // Max amount left for next deposits. If it is lower than the minimum\n // deposit amount, return 0.\n uint256 unusedLimit = maximumTotalAssets - currentTotalAssets;\n\n return minimumDepositAmount > unusedLimit ? 0 : unusedLimit;\n }\n\n /// @notice Returns the maximum amount of the vault shares that can be\n /// minted for the receiver, through a mint call.\n /// @dev Since the stBTC contract limits the maximum total tBTC tokens this\n /// function converts the maximum deposit amount to shares.\n /// @return The maximum amount of the vault shares.\n function maxMint(address receiver) public view override returns (uint256) {\n uint256 _maxDeposit = maxDeposit(receiver);\n\n // slither-disable-next-line incorrect-equality\n return\n _maxDeposit == type(uint256).max\n ? type(uint256).max\n : convertToShares(_maxDeposit);\n }\n\n /// @return Returns deposit parameters.\n function depositParameters() public view returns (uint256, uint256) {\n return (minimumDepositAmount, maximumTotalAssets);\n }\n\n /// @notice Redeems shares for tBTC tokens.\n function _entryFeeBasisPoints() internal view override returns (uint256) {\n return entryFeeBasisPoints;\n }\n\n /// @notice Returns the address of the treasury wallet, where fees should be\n /// transferred to.\n function _feeRecipient() internal view override returns (address) {\n return treasury;\n }\n}\n" - }, - "contracts/TbtcDepositor.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\n\nimport \"@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol\";\n\nimport {stBTC} from \"./stBTC.sol\";\n\n// TODO: Add Missfund token protection.\n// TODO: Make Upgradable\n\n/// @title tBTC Depositor contract.\n/// @notice The contract integrates Acre staking with tBTC minting.\n/// User who wants to stake BTC in Acre should submit a Bitcoin transaction\n/// to the most recently created off-chain ECDSA wallets of the tBTC Bridge\n/// using pay-to-script-hash (P2SH) or pay-to-witness-script-hash (P2WSH)\n/// containing hashed information about this Depositor contract address,\n/// and staker's Ethereum address.\n/// Then, the staker initiates tBTC minting by revealing their Ethereum\n/// address along with their deposit blinding factor, refund public key\n/// hash and refund locktime on the tBTC Bridge through this Depositor\n/// contract.\n/// The off-chain ECDSA wallet listens for these sorts of\n/// messages and when it gets one, it checks the Bitcoin network to make\n/// sure the deposit lines up. If it does, the off-chain ECDSA wallet\n/// may decide to pick the deposit transaction for sweeping, and when\n/// the sweep operation is confirmed on the Bitcoin network, the tBTC Bridge\n/// and tBTC vault mint the tBTC token to the Depositor address.\n/// After tBTC is minted to the Depositor, on the stake finalization\n/// tBTC is staked in stBTC contract and stBTC shares are emitted to the\n/// receiver pointed by the staker.\ncontract TbtcDepositor is AbstractTBTCDepositor, Ownable {\n using BTCUtils for bytes;\n using SafeERC20 for IERC20;\n\n struct StakeRequest {\n // Timestamp at which the deposit request was initialized is not stored\n // in this structure, as it is available under `Bridge.DepositRequest.revealedAt`.\n\n // UNIX timestamp at which the deposit request was finalized.\n // 0 if not yet finalized.\n uint64 finalizedAt;\n // The address to which the stBTC shares will be minted.\n address receiver;\n // Identifier of a partner in the referral program.\n uint16 referral;\n // tBTC token amount to stake after deducting tBTC minting fees and the\n // Depositor fee.\n uint256 amountToStake;\n }\n\n /// @notice tBTC Token contract.\n IERC20 public immutable tbtcToken;\n /// @notice stBTC contract.\n stBTC public immutable stbtc;\n\n /// @notice Mapping of stake requests.\n /// @dev The key is a deposit key identifying the deposit.\n mapping(uint256 => StakeRequest) public stakeRequests;\n\n /// @notice Divisor used to compute the depositor fee taken from each deposit\n /// and transferred to the treasury upon stake request finalization.\n /// @dev That fee is computed as follows:\n /// `depositorFee = depositedAmount / depositorFeeDivisor`\n /// for example, if the depositor fee needs to be 2% of each deposit,\n /// the `depositorFeeDivisor` should be set to `50` because\n /// `1/50 = 0.02 = 2%`.\n uint64 public depositorFeeDivisor;\n\n /// @notice Emitted when a stake request is initialized.\n /// @dev Deposit details can be fetched from {{ Bridge.DepositRevealed }}\n /// event emitted in the same transaction.\n /// @param depositKey Deposit key identifying the deposit.\n /// @param caller Address that initialized the stake request.\n /// @param receiver The address to which the stBTC shares will be minted.\n event StakeRequestInitialized(\n uint256 indexed depositKey,\n address indexed caller,\n address indexed receiver\n );\n\n /// @notice Emitted when bridging completion has been notified.\n /// @param depositKey Deposit key identifying the deposit.\n /// @param caller Address that notified about bridging completion.\n /// @param referral Identifier of a partner in the referral program.\n /// @param bridgedAmount Amount of tBTC tokens that was bridged by the tBTC bridge.\n /// @param depositorFee Depositor fee amount.\n event BridgingCompleted(\n uint256 indexed depositKey,\n address indexed caller,\n uint16 indexed referral,\n uint256 bridgedAmount,\n uint256 depositorFee\n );\n\n /// @notice Emitted when a stake request is finalized.\n /// @dev Deposit details can be fetched from {{ ERC4626.Deposit }}\n /// event emitted in the same transaction.\n /// @param depositKey Deposit key identifying the deposit.\n /// @param caller Address that finalized the stake request.\n /// @param amountToStake Amount of staked tBTC tokens.\n event StakeRequestFinalized(\n uint256 indexed depositKey,\n address indexed caller,\n uint256 amountToStake\n );\n\n /// @notice Emitted when a stake request is recalled.\n /// @param depositKey Deposit key identifying the deposit.\n /// @param receiver Address of the receiver.\n /// @param amountToStake Amount of recalled tBTC tokens.\n event StakeRequestRecalled(\n uint256 indexed depositKey,\n address indexed receiver,\n uint256 amountToStake\n );\n\n /// @notice Emitted when a depositor fee divisor is updated.\n /// @param depositorFeeDivisor New value of the depositor fee divisor.\n event DepositorFeeDivisorUpdated(uint64 depositorFeeDivisor);\n\n /// @dev Receiver address is zero.\n error ReceiverIsZeroAddress();\n\n /// @dev Attempted to finalize a stake request, while bridging completion has\n /// not been notified yet.\n error BridgingNotCompleted();\n\n /// @dev Calculated depositor fee exceeds the amount of minted tBTC tokens.\n error DepositorFeeExceedsBridgedAmount(\n uint256 depositorFee,\n uint256 bridgedAmount\n );\n\n /// @dev Attempted to finalize a stake request that was already finalized.\n error StakeRequestAlreadyFinalized();\n\n /// @dev Attempted to call function by an account that is not the receiver.\n error CallerNotReceiver();\n\n /// @notice Tbtc Depositor contract constructor.\n /// @param _bridge tBTC Bridge contract instance.\n /// @param _tbtcVault tBTC Vault contract instance.\n /// @param _stbtc stBTC contract instance.\n // TODO: Move to initializer when making the contract upgradeable.\n constructor(\n address _bridge,\n address _tbtcVault,\n address _tbtcToken,\n address _stbtc\n ) Ownable(msg.sender) {\n __AbstractTBTCDepositor_initialize(_bridge, _tbtcVault);\n\n require(_tbtcToken != address(0), \"TBTCToken address cannot be zero\");\n require(_stbtc != address(0), \"stBTC address cannot be zero\");\n\n tbtcToken = IERC20(_tbtcToken);\n stbtc = stBTC(_stbtc);\n\n depositorFeeDivisor = 1000; // 1/1000 == 10bps == 0.1% == 0.001\n }\n\n /// @notice This function allows staking process initialization for a Bitcoin\n /// deposit made by an user with a P2(W)SH transaction. It uses the\n /// supplied information to reveal a deposit to the tBTC Bridge contract.\n /// @dev Requirements:\n /// - The revealed vault address must match the TBTCVault address,\n /// - All requirements from {Bridge#revealDepositWithExtraData}\n /// function must be met.\n /// - `receiver` must be the receiver address used in the P2(W)SH BTC\n /// deposit transaction as part of the extra data.\n /// - `referral` must be the referral info used in the P2(W)SH BTC\n /// deposit transaction as part of the extra data.\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n /// @param fundingTx Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.\n /// @param reveal Deposit reveal data, see `IBridgeTypes.DepositRevealInfo`.\n /// @param receiver The address to which the stBTC shares will be minted.\n /// @param referral Data used for referral program.\n function initializeStakeRequest(\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\n IBridgeTypes.DepositRevealInfo calldata reveal,\n address receiver,\n uint16 referral\n ) external {\n if (receiver == address(0)) revert ReceiverIsZeroAddress();\n\n // We don't check if the request was already initialized, as this check\n // is enforced in `_initializeDeposit` when calling the\n // `Bridge.revealDepositWithExtraData` function.\n\n uint256 depositKey = _initializeDeposit(\n fundingTx,\n reveal,\n encodeExtraData(receiver, referral)\n );\n\n StakeRequest storage request = stakeRequests[depositKey];\n request.receiver = receiver;\n request.referral = referral;\n\n emit StakeRequestInitialized(depositKey, msg.sender, receiver);\n }\n\n /// @notice This function should be called for previously initialized stake\n /// request, after tBTC minting process completed, meaning tBTC was\n /// minted to this contract.\n /// @dev It calculates the amount to stake based on the approximate minted\n /// tBTC amount reduced by the depositor fee.\n /// @dev IMPORTANT NOTE: The minted tBTC amount used by this function is an\n /// approximation. See documentation of the\n /// {{TBTCDepositorProxy#_calculateTbtcAmount}} responsible for calculating\n /// this value for more details.\n /// @param depositKey Deposit key identifying the deposit.\n function notifyBridgingCompleted(uint256 depositKey) external {\n (\n uint256 depositAmount,\n uint256 depositSubBridgingFeesAmount,\n\n ) = _finalizeDeposit(depositKey);\n\n // Compute depositor fee. The fee is calculated based on the initial funding\n // transaction amount, before the tBTC protocol network fees were taken.\n uint256 depositorFee = depositorFeeDivisor > 0\n ? (depositAmount / depositorFeeDivisor)\n : 0;\n\n // Ensure the depositor fee does not exceed the approximate minted tBTC\n // amount.\n if (depositorFee >= depositSubBridgingFeesAmount) {\n revert DepositorFeeExceedsBridgedAmount(\n depositorFee,\n depositSubBridgingFeesAmount\n );\n }\n\n StakeRequest storage request = stakeRequests[depositKey];\n\n request.amountToStake = depositSubBridgingFeesAmount - depositorFee;\n\n emit BridgingCompleted(\n depositKey,\n msg.sender,\n request.referral,\n depositSubBridgingFeesAmount,\n depositorFee\n );\n\n // Transfer depositor fee to the treasury wallet.\n if (depositorFee > 0) {\n tbtcToken.safeTransfer(stbtc.treasury(), depositorFee);\n }\n }\n\n /// @notice This function should be called for previously initialized stake\n /// request, after tBTC bridging process was finalized.\n /// It stakes the tBTC from the given deposit into stBTC, emitting the\n /// stBTC shares to the receiver specified in the deposit extra data\n /// and using the referral provided in the extra data.\n /// @dev This function is expected to be called after `notifyBridgingCompleted`.\n /// In case depositing in stBTC vault fails (e.g. because of the\n /// maximum deposit limit being reached), the function should be retried\n /// after the limit is increased or other user withdraws their funds\n /// from the stBTC contract to make place for another deposit.\n /// The staker has a possibility to submit `recallStakeRequest` that\n /// will withdraw the minted tBTC token and abort staking process.\n /// @param depositKey Deposit key identifying the deposit.\n function finalizeStakeRequest(uint256 depositKey) external {\n StakeRequest storage request = stakeRequests[depositKey];\n\n if (request.amountToStake == 0) revert BridgingNotCompleted();\n if (request.finalizedAt > 0) revert StakeRequestAlreadyFinalized();\n\n // solhint-disable-next-line not-rely-on-time\n request.finalizedAt = uint64(block.timestamp);\n\n emit StakeRequestFinalized(\n depositKey,\n msg.sender,\n request.amountToStake\n );\n\n // Deposit tBTC in stBTC.\n tbtcToken.safeIncreaseAllowance(address(stbtc), request.amountToStake);\n // slither-disable-next-line unused-return\n stbtc.deposit(request.amountToStake, request.receiver);\n }\n\n /// @notice Recall bridged tBTC tokens from being requested to stake. This\n /// function can be called by the staker to recover tBTC that cannot\n /// be finalized to stake in stBTC contract due to a deposit limit being\n /// reached.\n /// @dev This function can be called only after bridging in tBTC Bridge was\n /// completed. Only receiver provided in the extra data of the stake\n /// request can call this function.\n /// @param depositKey Deposit key identifying the deposit.\n function recallStakeRequest(uint256 depositKey) external {\n StakeRequest storage request = stakeRequests[depositKey];\n\n if (request.amountToStake == 0) revert BridgingNotCompleted();\n if (request.finalizedAt > 0) revert StakeRequestAlreadyFinalized();\n\n // Check if caller is the receiver.\n if (msg.sender != request.receiver) revert CallerNotReceiver();\n\n // solhint-disable-next-line not-rely-on-time\n request.finalizedAt = uint64(block.timestamp);\n\n emit StakeRequestRecalled(\n depositKey,\n request.receiver,\n request.amountToStake\n );\n\n tbtcToken.safeTransfer(request.receiver, request.amountToStake);\n }\n\n /// @notice Updates the depositor fee divisor.\n /// @param newDepositorFeeDivisor New depositor fee divisor value.\n function updateDepositorFeeDivisor(\n uint64 newDepositorFeeDivisor\n ) external onlyOwner {\n // TODO: Introduce a parameters update process.\n depositorFeeDivisor = newDepositorFeeDivisor;\n\n emit DepositorFeeDivisorUpdated(newDepositorFeeDivisor);\n }\n\n // TODO: Handle minimum deposit amount in tBTC Bridge vs stBTC.\n\n /// @notice Encode receiver address and referral as extra data.\n /// @dev Packs the data to bytes32: 20 bytes of receiver address and\n /// 2 bytes of referral, 10 bytes of trailing zeros.\n /// @param receiver The address to which the stBTC shares will be minted.\n /// @param referral Data used for referral program.\n /// @return Encoded extra data.\n function encodeExtraData(\n address receiver,\n uint16 referral\n ) public pure returns (bytes32) {\n return bytes32(abi.encodePacked(receiver, referral));\n }\n}\n" - }, - "contracts/test/MockTbtcBridge.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport {MockBridge, MockTBTCVault} from \"@keep-network/tbtc-v2/contracts/test/TestTBTCDepositor.sol\";\nimport {IBridge} from \"@keep-network/tbtc-v2/contracts/integrator/IBridge.sol\";\nimport {IBridgeTypes} from \"@keep-network/tbtc-v2/contracts/integrator/IBridge.sol\";\n\nimport {TestERC20} from \"./TestERC20.sol\";\n\ncontract BridgeStub is MockBridge {}\n\ncontract TBTCVaultStub is MockTBTCVault {\n TestERC20 public immutable tbtc;\n IBridge public immutable bridge;\n\n /// @notice Multiplier to convert satoshi to TBTC token units.\n uint256 public constant SATOSHI_MULTIPLIER = 10 ** 10;\n\n constructor(TestERC20 _tbtc, IBridge _bridge) {\n tbtc = _tbtc;\n bridge = _bridge;\n }\n\n function finalizeOptimisticMintingRequestAndMint(\n uint256 depositKey\n ) public {\n MockTBTCVault.finalizeOptimisticMintingRequest(depositKey);\n\n IBridgeTypes.DepositRequest memory deposit = bridge.deposits(\n depositKey\n );\n\n uint256 amountSubTreasury = (deposit.amount - deposit.treasuryFee) *\n SATOSHI_MULTIPLIER;\n\n uint256 omFee = optimisticMintingFeeDivisor > 0\n ? (amountSubTreasury / optimisticMintingFeeDivisor)\n : 0;\n\n // The deposit transaction max fee is in the 1e8 satoshi precision.\n // We need to convert them to the 1e18 TBTC precision.\n // slither-disable-next-line unused-return\n (, , uint64 depositTxMaxFee, ) = bridge.depositParameters();\n uint256 txMaxFee = depositTxMaxFee * SATOSHI_MULTIPLIER;\n\n uint256 amountToMint = amountSubTreasury - omFee - txMaxFee;\n\n tbtc.mint(deposit.depositor, amountToMint);\n }\n}\n" - }, - "contracts/test/TestERC20.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract TestERC20 is ERC20 {\n constructor(string memory name, string memory symbol) ERC20(name, symbol) {}\n\n function mint(address account, uint256 value) external {\n _mint(account, value);\n }\n}\n" - }, - "contracts/test/TestERC4626.sol": { - "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.21;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\";\n\ncontract TestERC4626 is ERC4626 {\n constructor(\n IERC20 asset,\n string memory tokenName,\n string memory tokenSymbol\n ) ERC4626(asset) ERC20(tokenName, tokenSymbol) {}\n}\n" - } - }, - "settings": { - "optimizer": { - "enabled": true, - "runs": 1000 - }, - "evmVersion": "paris", - "outputSelection": { - "*": { - "*": [ - "abi", - "evm.bytecode", - "evm.deployedBytecode", - "evm.methodIdentifiers", - "metadata", - "devdoc", - "userdoc", - "storageLayout", - "evm.gasEstimates" - ], - "": [ - "ast" - ] - } - }, - "metadata": { - "useLiteralContent": true - } - } -} \ No newline at end of file diff --git a/solidity/deployments/sepolia/stBTC.json b/solidity/deployments/sepolia/stBTC.json index d3587e993..a8a2e9892 100644 --- a/solidity/deployments/sepolia/stBTC.json +++ b/solidity/deployments/sepolia/stBTC.json @@ -1,19 +1,8 @@ { - "address": "0xF99139f09164B092bD9e8558984Becfb0d2eCb87", + "address": "0xc14972DC5a4443E4f5e89E3655BE48Ee95A795aB", "abi": [ { - "inputs": [ - { - "internalType": "contract IERC20", - "name": "_tbtc", - "type": "address" - }, - { - "internalType": "address", - "name": "_treasury", - "type": "address" - } - ], + "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, @@ -214,11 +203,26 @@ "name": "ERC4626ExceededMaxWithdraw", "type": "error" }, + { + "inputs": [], + "name": "EnforcedPause", + "type": "error" + }, + { + "inputs": [], + "name": "ExpectedPause", + "type": "error" + }, { "inputs": [], "name": "FailedInnerCall", "type": "error" }, + { + "inputs": [], + "name": "InvalidInitialization", + "type": "error" + }, { "inputs": [ { @@ -240,6 +244,11 @@ "name": "MathOverflowedMulDiv", "type": "error" }, + { + "inputs": [], + "name": "NotInitializing", + "type": "error" + }, { "inputs": [ { @@ -262,6 +271,17 @@ "name": "OwnableUnauthorizedAccount", "type": "error" }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "PausableUnauthorizedAccount", + "type": "error" + }, { "inputs": [ { @@ -339,18 +359,31 @@ "inputs": [ { "indexed": false, - "internalType": "uint256", - "name": "minimumDepositAmount", - "type": "uint256" + "internalType": "address", + "name": "oldDispatcher", + "type": "address" }, + { + "indexed": false, + "internalType": "address", + "name": "newDispatcher", + "type": "address" + } + ], + "name": "DispatcherUpdated", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ { "indexed": false, "internalType": "uint256", - "name": "maximumTotalAssets", + "name": "entryFeeBasisPoints", "type": "uint256" } ], - "name": "DepositParametersUpdated", + "name": "EntryFeeBasisPointsUpdated", "type": "event" }, { @@ -358,18 +391,25 @@ "inputs": [ { "indexed": false, - "internalType": "address", - "name": "oldDispatcher", - "type": "address" - }, + "internalType": "uint256", + "name": "exitFeeBasisPoints", + "type": "uint256" + } + ], + "name": "ExitFeeBasisPointsUpdated", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ { "indexed": false, - "internalType": "address", - "name": "newDispatcher", - "type": "address" + "internalType": "uint64", + "name": "version", + "type": "uint64" } ], - "name": "DispatcherUpdated", + "name": "Initialized", "type": "event" }, { @@ -378,11 +418,11 @@ { "indexed": false, "internalType": "uint256", - "name": "entryFeeBasisPoints", + "name": "minimumDepositAmount", "type": "uint256" } ], - "name": "EntryFeeBasisPointsUpdated", + "name": "MinimumDepositAmountUpdated", "type": "event" }, { @@ -401,7 +441,7 @@ "type": "address" } ], - "name": "OwnershipTransferred", + "name": "OwnershipTransferStarted", "type": "event" }, { @@ -409,18 +449,50 @@ "inputs": [ { "indexed": true, - "internalType": "uint16", - "name": "referral", - "type": "uint16" + "internalType": "address", + "name": "previousOwner", + "type": "address" }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ { "indexed": false, - "internalType": "uint256", - "name": "assets", - "type": "uint256" + "internalType": "address", + "name": "newAccount", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "oldAccount", + "type": "address" } ], - "name": "StakeReferral", + "name": "PauseAdminUpdated", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Paused", "type": "event" }, { @@ -454,13 +526,32 @@ { "indexed": false, "internalType": "address", - "name": "treasury", + "name": "oldTreasury", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newTreasury", "type": "address" } ], "name": "TreasuryUpdated", "type": "event" }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Unpaused", + "type": "event" + }, { "anonymous": false, "inputs": [ @@ -498,6 +589,13 @@ "name": "Withdraw", "type": "event" }, + { + "inputs": [], + "name": "acceptOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, { "inputs": [ { @@ -546,6 +644,35 @@ "stateMutability": "nonpayable", "type": "function" }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "extraData", + "type": "bytes" + } + ], + "name": "approveAndCall", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, { "inputs": [], "name": "asset", @@ -559,6 +686,25 @@ "stateMutability": "view", "type": "function" }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "assetsBalanceOf", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, { "inputs": [ { @@ -655,17 +801,12 @@ }, { "inputs": [], - "name": "depositParameters", + "name": "dispatcher", "outputs": [ { - "internalType": "uint256", + "internalType": "contract IDispatcher", "name": "", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "", - "type": "uint256" + "type": "address" } ], "stateMutability": "view", @@ -673,12 +814,12 @@ }, { "inputs": [], - "name": "dispatcher", + "name": "entryFeeBasisPoints", "outputs": [ { - "internalType": "contract Dispatcher", + "internalType": "uint256", "name": "", - "type": "address" + "type": "uint256" } ], "stateMutability": "view", @@ -686,7 +827,7 @@ }, { "inputs": [], - "name": "entryFeeBasisPoints", + "name": "exitFeeBasisPoints", "outputs": [ { "internalType": "uint256", @@ -697,6 +838,24 @@ "stateMutability": "view", "type": "function" }, + { + "inputs": [ + { + "internalType": "contract IERC20", + "name": "asset", + "type": "address" + }, + { + "internalType": "address", + "name": "_treasury", + "type": "address" + } + ], + "name": "initialize", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, { "inputs": [ { @@ -720,7 +879,7 @@ "inputs": [ { "internalType": "address", - "name": "receiver", + "name": "", "type": "address" } ], @@ -773,19 +932,6 @@ "stateMutability": "view", "type": "function" }, - { - "inputs": [], - "name": "maximumTotalAssets", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, { "inputs": [], "name": "minimumDepositAmount", @@ -849,6 +995,52 @@ "stateMutability": "view", "type": "function" }, + { + "inputs": [], + "name": "pause", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "pauseAdmin", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "paused", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "pendingOwner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, { "inputs": [ { @@ -961,35 +1153,6 @@ "stateMutability": "nonpayable", "type": "function" }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "assets", - "type": "uint256" - }, - { - "internalType": "address", - "name": "receiver", - "type": "address" - }, - { - "internalType": "uint16", - "name": "referral", - "type": "uint16" - } - ], - "name": "stake", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, { "inputs": [], "name": "symbol", @@ -1108,20 +1271,35 @@ "stateMutability": "view", "type": "function" }, + { + "inputs": [], + "name": "unpause", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, { "inputs": [ { - "internalType": "uint256", - "name": "_minimumDepositAmount", - "type": "uint256" - }, + "internalType": "contract IDispatcher", + "name": "newDispatcher", + "type": "address" + } + ], + "name": "updateDispatcher", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ { "internalType": "uint256", - "name": "_maximumTotalAssets", + "name": "newEntryFeeBasisPoints", "type": "uint256" } ], - "name": "updateDepositParameters", + "name": "updateEntryFeeBasisPoints", "outputs": [], "stateMutability": "nonpayable", "type": "function" @@ -1129,12 +1307,12 @@ { "inputs": [ { - "internalType": "contract Dispatcher", - "name": "newDispatcher", - "type": "address" + "internalType": "uint256", + "name": "newExitFeeBasisPoints", + "type": "uint256" } ], - "name": "updateDispatcher", + "name": "updateExitFeeBasisPoints", "outputs": [], "stateMutability": "nonpayable", "type": "function" @@ -1143,11 +1321,24 @@ "inputs": [ { "internalType": "uint256", - "name": "newEntryFeeBasisPoints", + "name": "newMinimumDepositAmount", "type": "uint256" } ], - "name": "updateEntryFeeBasisPoints", + "name": "updateMinimumDepositAmount", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newPauseAdmin", + "type": "address" + } + ], + "name": "updatePauseAdmin", "outputs": [], "stateMutability": "nonpayable", "type": "function" @@ -1195,554 +1386,8 @@ "type": "function" } ], - "transactionHash": "0xe391d9f8196548e08172cd330bfe61a0c75e5825b29319f981a97854f5ee67b6", - "receipt": { - "to": null, - "from": "0x2d154A5c7cE9939274b89bbCe9f5B069E57b09A8", - "contractAddress": "0xF99139f09164B092bD9e8558984Becfb0d2eCb87", - "transactionIndex": 82, - "gasUsed": "1951493", - "logsBloom": "0x00000000000000000000000000000000000000000000000000800000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001008000000000000000000000000000400000020000000000000000000800000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000012000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0xb2d302740b02f4ae8a4b18dcdbfbcc9d608d5e8accbb33e3daa7f98fdccac21e", - "transactionHash": "0xe391d9f8196548e08172cd330bfe61a0c75e5825b29319f981a97854f5ee67b6", - "logs": [ - { - "transactionIndex": 82, - "blockNumber": 5206357, - "transactionHash": "0xe391d9f8196548e08172cd330bfe61a0c75e5825b29319f981a97854f5ee67b6", - "address": "0xF99139f09164B092bD9e8558984Becfb0d2eCb87", - "topics": [ - "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", - "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x0000000000000000000000002d154a5c7ce9939274b89bbce9f5b069e57b09a8" - ], - "data": "0x", - "logIndex": 230, - "blockHash": "0xb2d302740b02f4ae8a4b18dcdbfbcc9d608d5e8accbb33e3daa7f98fdccac21e" - } - ], - "blockNumber": 5206357, - "cumulativeGasUsed": "13353873", - "status": 1, - "byzantium": true - }, - "args": [ - "0x517f2982701695D4E52f1ECFBEf3ba31Df470161", - "0x2d154A5c7cE9939274b89bbCe9f5B069E57b09A8" - ], + "transactionHash": "0x86123a76a3d2e04e1d1d925635a72165d75e10b245cf9a0c67ea7edb05514bad", "numDeployments": 1, - "solcInputHash": "b22c277b248ba02f9ec5bf62d176f9ce", - "metadata": "{\"compiler\":{\"version\":\"0.8.21+commit.d9974bed\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"contract IERC20\",\"name\":\"_tbtc\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_treasury\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"}],\"name\":\"AddressEmptyCode\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"AddressInsufficientBalance\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DisallowedAddress\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"allowance\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"needed\",\"type\":\"uint256\"}],\"name\":\"ERC20InsufficientAllowance\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"balance\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"needed\",\"type\":\"uint256\"}],\"name\":\"ERC20InsufficientBalance\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"approver\",\"type\":\"address\"}],\"name\":\"ERC20InvalidApprover\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"ERC20InvalidReceiver\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"ERC20InvalidSender\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"ERC20InvalidSpender\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"}],\"name\":\"ERC4626ExceededMaxDeposit\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"}],\"name\":\"ERC4626ExceededMaxMint\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"}],\"name\":\"ERC4626ExceededMaxRedeem\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"}],\"name\":\"ERC4626ExceededMaxWithdraw\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"FailedInnerCall\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"min\",\"type\":\"uint256\"}],\"name\":\"LessThanMinDeposit\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"MathOverflowedMulDiv\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"OwnableInvalidOwner\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"OwnableUnauthorizedAccount\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"SafeERC20FailedOperation\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroAddress\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"Deposit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"minimumDepositAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"maximumTotalAssets\",\"type\":\"uint256\"}],\"name\":\"DepositParametersUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"oldDispatcher\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newDispatcher\",\"type\":\"address\"}],\"name\":\"DispatcherUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"entryFeeBasisPoints\",\"type\":\"uint256\"}],\"name\":\"EntryFeeBasisPointsUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint16\",\"name\":\"referral\",\"type\":\"uint16\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"StakeReferral\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"treasury\",\"type\":\"address\"}],\"name\":\"TreasuryUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"Withdraw\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"asset\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"convertToAssets\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"convertToShares\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"deposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"depositParameters\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"dispatcher\",\"outputs\":[{\"internalType\":\"contract Dispatcher\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"entryFeeBasisPoints\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"maxDeposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"maxMint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"maxRedeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"maxWithdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"maximumTotalAssets\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"minimumDepositAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"mint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"previewDeposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"previewMint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"previewRedeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"previewWithdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"redeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"uint16\",\"name\":\"referral\",\"type\":\"uint16\"}],\"name\":\"stake\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalAssets\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"treasury\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_minimumDepositAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_maximumTotalAssets\",\"type\":\"uint256\"}],\"name\":\"updateDepositParameters\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contract Dispatcher\",\"name\":\"newDispatcher\",\"type\":\"address\"}],\"name\":\"updateDispatcher\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"newEntryFeeBasisPoints\",\"type\":\"uint256\"}],\"name\":\"updateEntryFeeBasisPoints\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newTreasury\",\"type\":\"address\"}],\"name\":\"updateTreasury\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"withdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"details\":\"ERC-4626 is a standard to optimize and unify the technical parameters of yield-bearing vaults. This contract facilitates the minting and burning of shares (stBTC), which are represented as standard ERC20 tokens, providing a seamless exchange with tBTC tokens.\",\"errors\":{\"AddressEmptyCode(address)\":[{\"details\":\"There's no code at `target` (it is not a contract).\"}],\"AddressInsufficientBalance(address)\":[{\"details\":\"The ETH balance of the account is not enough to perform the operation.\"}],\"ERC20InsufficientAllowance(address,uint256,uint256)\":[{\"details\":\"Indicates a failure with the `spender`\\u2019s `allowance`. Used in transfers.\",\"params\":{\"allowance\":\"Amount of tokens a `spender` is allowed to operate with.\",\"needed\":\"Minimum amount required to perform a transfer.\",\"spender\":\"Address that may be allowed to operate on tokens without being their owner.\"}}],\"ERC20InsufficientBalance(address,uint256,uint256)\":[{\"details\":\"Indicates an error related to the current `balance` of a `sender`. Used in transfers.\",\"params\":{\"balance\":\"Current balance for the interacting account.\",\"needed\":\"Minimum amount required to perform a transfer.\",\"sender\":\"Address whose tokens are being transferred.\"}}],\"ERC20InvalidApprover(address)\":[{\"details\":\"Indicates a failure with the `approver` of a token to be approved. Used in approvals.\",\"params\":{\"approver\":\"Address initiating an approval operation.\"}}],\"ERC20InvalidReceiver(address)\":[{\"details\":\"Indicates a failure with the token `receiver`. Used in transfers.\",\"params\":{\"receiver\":\"Address to which tokens are being transferred.\"}}],\"ERC20InvalidSender(address)\":[{\"details\":\"Indicates a failure with the token `sender`. Used in transfers.\",\"params\":{\"sender\":\"Address whose tokens are being transferred.\"}}],\"ERC20InvalidSpender(address)\":[{\"details\":\"Indicates a failure with the `spender` to be approved. Used in approvals.\",\"params\":{\"spender\":\"Address that may be allowed to operate on tokens without being their owner.\"}}],\"ERC4626ExceededMaxDeposit(address,uint256,uint256)\":[{\"details\":\"Attempted to deposit more assets than the max amount for `receiver`.\"}],\"ERC4626ExceededMaxMint(address,uint256,uint256)\":[{\"details\":\"Attempted to mint more shares than the max amount for `receiver`.\"}],\"ERC4626ExceededMaxRedeem(address,uint256,uint256)\":[{\"details\":\"Attempted to redeem more shares than the max amount for `receiver`.\"}],\"ERC4626ExceededMaxWithdraw(address,uint256,uint256)\":[{\"details\":\"Attempted to withdraw more assets than the max amount for `receiver`.\"}],\"FailedInnerCall()\":[{\"details\":\"A call to an address target failed. The target may have reverted.\"}],\"LessThanMinDeposit(uint256,uint256)\":[{\"params\":{\"amount\":\"Amount to check.\",\"min\":\"Minimum amount to check 'amount' against.\"}}],\"MathOverflowedMulDiv()\":[{\"details\":\"Muldiv operation overflow.\"}],\"OwnableInvalidOwner(address)\":[{\"details\":\"The owner is not a valid owner account. (eg. `address(0)`)\"}],\"OwnableUnauthorizedAccount(address)\":[{\"details\":\"The caller account is not authorized to perform an operation.\"}],\"SafeERC20FailedOperation(address)\":[{\"details\":\"An operation with an ERC20 token failed.\"}]},\"events\":{\"Approval(address,address,uint256)\":{\"details\":\"Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance.\"},\"DepositParametersUpdated(uint256,uint256)\":{\"params\":{\"maximumTotalAssets\":\"New value of the maximum total assets amount.\",\"minimumDepositAmount\":\"New value of the minimum deposit amount.\"}},\"DispatcherUpdated(address,address)\":{\"params\":{\"newDispatcher\":\"Address of the new dispatcher contract.\",\"oldDispatcher\":\"Address of the old dispatcher contract.\"}},\"EntryFeeBasisPointsUpdated(uint256)\":{\"params\":{\"entryFeeBasisPoints\":\"New value of the fee basis points.\"}},\"StakeReferral(uint16,uint256)\":{\"params\":{\"assets\":\"Amount of tBTC tokens staked.\",\"referral\":\"Used for referral program.\"}},\"Transfer(address,address,uint256)\":{\"details\":\"Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero.\"},\"TreasuryUpdated(address)\":{\"params\":{\"treasury\":\"New treasury wallet address.\"}}},\"kind\":\"dev\",\"methods\":{\"allowance(address,address)\":{\"details\":\"See {IERC20-allowance}.\"},\"approve(address,uint256)\":{\"details\":\"See {IERC20-approve}. NOTE: If `value` is the maximum `uint256`, the allowance is not updated on `transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address.\"},\"asset()\":{\"details\":\"See {IERC4626-asset}. \"},\"balanceOf(address)\":{\"details\":\"See {IERC20-balanceOf}.\"},\"convertToAssets(uint256)\":{\"details\":\"See {IERC4626-convertToAssets}. \"},\"convertToShares(uint256)\":{\"details\":\"See {IERC4626-convertToShares}. \"},\"decimals()\":{\"details\":\"Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This \\\"original\\\" value is cached during construction of the vault contract. If this read operation fails (e.g., the asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals. See {IERC20Metadata-decimals}.\"},\"deposit(uint256,address)\":{\"details\":\"Takes into account a deposit parameter, minimum deposit amount, which determines the minimum amount for a single deposit operation. The amount of the assets has to be pre-approved in the tBTC contract.\",\"params\":{\"assets\":\"Approved amount of tBTC tokens to deposit. This includes treasury fees for staking tBTC.\",\"receiver\":\"The address to which the shares will be minted.\"},\"returns\":{\"_0\":\"Minted shares adjusted for the fees taken by the treasury.\"}},\"depositParameters()\":{\"returns\":{\"_0\":\"Returns deposit parameters.\"}},\"maxDeposit(address)\":{\"returns\":{\"_0\":\"The maximum amount of tBTC token that can be deposited into Acre protocol for the receiver.\"}},\"maxMint(address)\":{\"details\":\"Since the stBTC contract limits the maximum total tBTC tokens this function converts the maximum deposit amount to shares.\",\"returns\":{\"_0\":\"The maximum amount of the vault shares.\"}},\"maxRedeem(address)\":{\"details\":\"See {IERC4626-maxRedeem}. \"},\"maxWithdraw(address)\":{\"details\":\"See {IERC4626-maxWithdraw}. \"},\"mint(uint256,address)\":{\"details\":\"Takes into account a deposit parameter, minimum deposit amount, which determines the minimum amount for a single deposit operation. The amount of the assets has to be pre-approved in the tBTC contract. The msg.sender is required to grant approval for the transfer of a certain amount of tBTC, and in addition, approval for the associated fee. Specifically, the total amount to be approved (amountToApprove) should be equal to the sum of the deposited amount and the fee. To determine the total assets amount necessary for approval corresponding to a given share amount, use the `previewMint` function.\",\"params\":{\"receiver\":\"The address to which the shares will be minted.\",\"shares\":\"Amount of shares to mint.\"}},\"name()\":{\"details\":\"Returns the name of the token.\"},\"owner()\":{\"details\":\"Returns the address of the current owner.\"},\"previewDeposit(uint256)\":{\"details\":\"Preview taking an entry fee on deposit. See {IERC4626-previewDeposit}.\"},\"previewMint(uint256)\":{\"details\":\"Preview adding an entry fee on mint. See {IERC4626-previewMint}.\"},\"previewRedeem(uint256)\":{\"details\":\"See {IERC4626-previewRedeem}. \"},\"previewWithdraw(uint256)\":{\"details\":\"See {IERC4626-previewWithdraw}. \"},\"redeem(uint256,address,address)\":{\"details\":\"See {IERC4626-redeem}. \"},\"renounceOwnership()\":{\"details\":\"Leaves the contract without owner. It will not be possible to call `onlyOwner` functions. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby disabling any functionality that is only available to the owner.\"},\"stake(uint256,address,uint16)\":{\"details\":\"This function calls `deposit` function from `ERC4626` contract. The amount of the assets has to be pre-approved in the tBTC contract.\",\"params\":{\"assets\":\"Approved amount for the transfer and stake.\",\"receiver\":\"The address to which the shares will be minted.\",\"referral\":\"Data used for referral program.\"},\"returns\":{\"_0\":\"shares Minted shares.\"}},\"symbol()\":{\"details\":\"Returns the symbol of the token, usually a shorter version of the name.\"},\"totalAssets()\":{\"details\":\"See {IERC4626-totalAssets}. \"},\"totalSupply()\":{\"details\":\"See {IERC20-totalSupply}.\"},\"transfer(address,uint256)\":{\"details\":\"See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `value`.\"},\"transferFrom(address,address,uint256)\":{\"details\":\"See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowance is the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address. - `from` must have a balance of at least `value`. - the caller must have allowance for ``from``'s tokens of at least `value`.\"},\"transferOwnership(address)\":{\"details\":\"Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.\"},\"updateDepositParameters(uint256,uint256)\":{\"details\":\"To disable the limit for deposits, set the maximum total assets to maximum (`type(uint256).max`).\",\"params\":{\"_maximumTotalAssets\":\"New value of the maximum total assets amount. It is the maximum amount of the tBTC token that the Acre protocol can hold.\",\"_minimumDepositAmount\":\"New value of the minimum deposit amount. It is the minimum amount for a single deposit operation.\"}},\"updateDispatcher(address)\":{\"params\":{\"newDispatcher\":\"Address of the new dispatcher contract.\"}},\"updateEntryFeeBasisPoints(uint256)\":{\"params\":{\"newEntryFeeBasisPoints\":\"New value of the fee basis points.\"}},\"updateTreasury(address)\":{\"params\":{\"newTreasury\":\"New treasury wallet address.\"}},\"withdraw(uint256,address,address)\":{\"details\":\"See {IERC4626-withdraw}. \"}},\"title\":\"stBTC\",\"version\":1},\"userdoc\":{\"errors\":{\"DisallowedAddress()\":[{\"notice\":\"Reverts if the address is disallowed.\"}],\"LessThanMinDeposit(uint256,uint256)\":[{\"notice\":\"Reverts if the amount is less than the minimum deposit amount.\"}],\"ZeroAddress()\":[{\"notice\":\"Reverts if the address is zero.\"}]},\"events\":{\"DepositParametersUpdated(uint256,uint256)\":{\"notice\":\"Emitted when deposit parameters are updated.\"},\"DispatcherUpdated(address,address)\":{\"notice\":\"Emitted when the dispatcher contract is updated.\"},\"EntryFeeBasisPointsUpdated(uint256)\":{\"notice\":\"Emitted when the entry fee basis points are updated.\"},\"StakeReferral(uint16,uint256)\":{\"notice\":\"Emitted when a referral is used.\"},\"TreasuryUpdated(address)\":{\"notice\":\"Emitted when the treasury wallet address is updated.\"}},\"kind\":\"user\",\"methods\":{\"deposit(uint256,address)\":{\"notice\":\"Mints shares to receiver by depositing exactly amount of tBTC tokens.\"},\"dispatcher()\":{\"notice\":\"Dispatcher contract that routes tBTC from stBTC to a given vault and back.\"},\"entryFeeBasisPoints()\":{\"notice\":\"Entry fee basis points applied to entry fee calculation.\"},\"maxDeposit(address)\":{\"notice\":\"Returns the maximum amount of the tBTC token that can be deposited into the vault for the receiver through a deposit call. It takes into account the deposit parameter, maximum total assets, which determines the total amount of tBTC token held by Acre. This function always returns available limit for deposits, but the fee is not taken into account. As a result of this, there always will be some dust left. If the dust is lower than the minimum deposit amount, this function will return 0.\"},\"maxMint(address)\":{\"notice\":\"Returns the maximum amount of the vault shares that can be minted for the receiver, through a mint call.\"},\"maximumTotalAssets()\":{\"notice\":\"Maximum total amount of tBTC token held by Acre protocol.\"},\"minimumDepositAmount()\":{\"notice\":\"Minimum amount for a single deposit operation. The value should be set low enough so the deposits routed through TbtcDepositor contract won't be rejected. It means that minimumDepositAmount should be lower than tBTC protocol's depositDustThreshold reduced by all the minting fees taken before depositing in the Acre contract.\"},\"mint(uint256,address)\":{\"notice\":\"Mints shares to receiver by depositing tBTC tokens.\"},\"stake(uint256,address,uint16)\":{\"notice\":\"Stakes a given amount of tBTC token and mints shares to a receiver.\"},\"treasury()\":{\"notice\":\"Address of the treasury wallet, where fees should be transferred to.\"},\"updateDepositParameters(uint256,uint256)\":{\"notice\":\"Updates deposit parameters.\"},\"updateDispatcher(address)\":{\"notice\":\"Updates the dispatcher contract and gives it an unlimited allowance to transfer staked tBTC.\"},\"updateEntryFeeBasisPoints(uint256)\":{\"notice\":\"Update the entry fee basis points.\"},\"updateTreasury(address)\":{\"notice\":\"Updates treasury wallet address.\"}},\"notice\":\"This contract implements the ERC-4626 tokenized vault standard. By staking tBTC, users acquire a liquid staking token called stBTC, commonly referred to as \\\"shares\\\". The staked tBTC is securely deposited into Acre's vaults, where it generates yield over time. Users have the flexibility to redeem stBTC, enabling them to withdraw their staked tBTC along with the accrued yield.\",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/stBTC.sol\":\"stBTC\"},\"evmVersion\":\"paris\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":1000},\"remappings\":[]},\"sources\":{\"@openzeppelin/contracts/access/Ownable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {Context} from \\\"../utils/Context.sol\\\";\\n\\n/**\\n * @dev Contract module which provides a basic access control mechanism, where\\n * there is an account (an owner) that can be granted exclusive access to\\n * specific functions.\\n *\\n * The initial owner is set to the address provided by the deployer. This can\\n * later be changed with {transferOwnership}.\\n *\\n * This module is used through inheritance. It will make available the modifier\\n * `onlyOwner`, which can be applied to your functions to restrict their use to\\n * the owner.\\n */\\nabstract contract Ownable is Context {\\n address private _owner;\\n\\n /**\\n * @dev The caller account is not authorized to perform an operation.\\n */\\n error OwnableUnauthorizedAccount(address account);\\n\\n /**\\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\\n */\\n error OwnableInvalidOwner(address owner);\\n\\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\\n\\n /**\\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\\n */\\n constructor(address initialOwner) {\\n if (initialOwner == address(0)) {\\n revert OwnableInvalidOwner(address(0));\\n }\\n _transferOwnership(initialOwner);\\n }\\n\\n /**\\n * @dev Throws if called by any account other than the owner.\\n */\\n modifier onlyOwner() {\\n _checkOwner();\\n _;\\n }\\n\\n /**\\n * @dev Returns the address of the current owner.\\n */\\n function owner() public view virtual returns (address) {\\n return _owner;\\n }\\n\\n /**\\n * @dev Throws if the sender is not the owner.\\n */\\n function _checkOwner() internal view virtual {\\n if (owner() != _msgSender()) {\\n revert OwnableUnauthorizedAccount(_msgSender());\\n }\\n }\\n\\n /**\\n * @dev Leaves the contract without owner. It will not be possible to call\\n * `onlyOwner` functions. Can only be called by the current owner.\\n *\\n * NOTE: Renouncing ownership will leave the contract without an owner,\\n * thereby disabling any functionality that is only available to the owner.\\n */\\n function renounceOwnership() public virtual onlyOwner {\\n _transferOwnership(address(0));\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Can only be called by the current owner.\\n */\\n function transferOwnership(address newOwner) public virtual onlyOwner {\\n if (newOwner == address(0)) {\\n revert OwnableInvalidOwner(address(0));\\n }\\n _transferOwnership(newOwner);\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Internal function without access restriction.\\n */\\n function _transferOwnership(address newOwner) internal virtual {\\n address oldOwner = _owner;\\n _owner = newOwner;\\n emit OwnershipTransferred(oldOwner, newOwner);\\n }\\n}\\n\",\"keccak256\":\"0xff6d0bb2e285473e5311d9d3caacb525ae3538a80758c10649a4d61029b017bb\",\"license\":\"MIT\"},\"@openzeppelin/contracts/interfaces/IERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../token/ERC20/IERC20.sol\\\";\\nimport {IERC20Metadata} from \\\"../token/ERC20/extensions/IERC20Metadata.sol\\\";\\n\\n/**\\n * @dev Interface of the ERC4626 \\\"Tokenized Vault Standard\\\", as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\\n */\\ninterface IERC4626 is IERC20, IERC20Metadata {\\n event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\\n\\n event Withdraw(\\n address indexed sender,\\n address indexed receiver,\\n address indexed owner,\\n uint256 assets,\\n uint256 shares\\n );\\n\\n /**\\n * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\\n *\\n * - MUST be an ERC-20 token contract.\\n * - MUST NOT revert.\\n */\\n function asset() external view returns (address assetTokenAddress);\\n\\n /**\\n * @dev Returns the total amount of the underlying asset that is \\u201cmanaged\\u201d by Vault.\\n *\\n * - SHOULD include any compounding that occurs from yield.\\n * - MUST be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT revert.\\n */\\n function totalAssets() external view returns (uint256 totalManagedAssets);\\n\\n /**\\n * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToShares(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\\n * through a deposit call.\\n *\\n * - MUST return a limited value if receiver is subject to some deposit limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\\n * - MUST NOT revert.\\n */\\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\\n * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\\n * in the same transaction.\\n * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\\n * deposit would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * deposit execution, and are accounted for during deposit.\\n * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\\n * - MUST return a limited value if receiver is subject to some mint limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\\n * - MUST NOT revert.\\n */\\n function maxMint(address receiver) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\\n * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\\n * same transaction.\\n * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\\n * would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by minting.\\n */\\n function previewMint(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\\n * execution, and are accounted for during mint.\\n * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\\n * Vault, through a withdraw call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\\n * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\\n * called\\n * in the same transaction.\\n * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\\n * the withdrawal would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * withdraw execution, and are accounted for during withdraw.\\n * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\\n * through a redeem call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxRedeem(address owner) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\\n * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\\n * same transaction.\\n * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\\n * redemption would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\\n */\\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * redeem execution, and are accounted for during redeem.\\n * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\\n}\\n\",\"keccak256\":\"0x207f64371bc0fcc5be86713aa5da109a870cc3a6da50e93b64ee881e369b593d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Standard ERC20 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.\\n */\\ninterface IERC20Errors {\\n /**\\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param balance Current balance for the interacting account.\\n * @param needed Minimum amount required to perform a transfer.\\n */\\n error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC20InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC20InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `spender`\\u2019s `allowance`. Used in transfers.\\n * @param spender Address that may be allowed to operate on tokens without being their owner.\\n * @param allowance Amount of tokens a `spender` is allowed to operate with.\\n * @param needed Minimum amount required to perform a transfer.\\n */\\n error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC20InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\\n * @param spender Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC20InvalidSpender(address spender);\\n}\\n\\n/**\\n * @dev Standard ERC721 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.\\n */\\ninterface IERC721Errors {\\n /**\\n * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.\\n * Used in balance queries.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC721InvalidOwner(address owner);\\n\\n /**\\n * @dev Indicates a `tokenId` whose `owner` is the zero address.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC721NonexistentToken(uint256 tokenId);\\n\\n /**\\n * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param tokenId Identifier number of a token.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC721InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC721InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `operator`\\u2019s approval. Used in transfers.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC721InsufficientApproval(address operator, uint256 tokenId);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC721InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC721InvalidOperator(address operator);\\n}\\n\\n/**\\n * @dev Standard ERC1155 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.\\n */\\ninterface IERC1155Errors {\\n /**\\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param balance Current balance for the interacting account.\\n * @param needed Minimum amount required to perform a transfer.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC1155InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC1155InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `operator`\\u2019s approval. Used in transfers.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC1155MissingApprovalForAll(address operator, address owner);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC1155InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC1155InvalidOperator(address operator);\\n\\n /**\\n * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\\n * Used in batch transfers.\\n * @param idsLength Length of the array of token identifiers\\n * @param valuesLength Length of the array of token amounts\\n */\\n error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\\n}\\n\",\"keccak256\":\"0x60c65f701957fdd6faea1acb0bb45825791d473693ed9ecb34726fdfaa849dd7\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/ERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"./IERC20.sol\\\";\\nimport {IERC20Metadata} from \\\"./extensions/IERC20Metadata.sol\\\";\\nimport {Context} from \\\"../../utils/Context.sol\\\";\\nimport {IERC20Errors} from \\\"../../interfaces/draft-IERC6093.sol\\\";\\n\\n/**\\n * @dev Implementation of the {IERC20} interface.\\n *\\n * This implementation is agnostic to the way tokens are created. This means\\n * that a supply mechanism has to be added in a derived contract using {_mint}.\\n *\\n * TIP: For a detailed writeup see our guide\\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\\n * to implement supply mechanisms].\\n *\\n * The default value of {decimals} is 18. To change this, you should override\\n * this function so it returns a different value.\\n *\\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\\n * instead returning `false` on failure. This behavior is nonetheless\\n * conventional and does not conflict with the expectations of ERC20\\n * applications.\\n *\\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\\n * This allows applications to reconstruct the allowance for all accounts just\\n * by listening to said events. Other implementations of the EIP may not emit\\n * these events, as it isn't required by the specification.\\n */\\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\\n mapping(address account => uint256) private _balances;\\n\\n mapping(address account => mapping(address spender => uint256)) private _allowances;\\n\\n uint256 private _totalSupply;\\n\\n string private _name;\\n string private _symbol;\\n\\n /**\\n * @dev Sets the values for {name} and {symbol}.\\n *\\n * All two of these values are immutable: they can only be set once during\\n * construction.\\n */\\n constructor(string memory name_, string memory symbol_) {\\n _name = name_;\\n _symbol = symbol_;\\n }\\n\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() public view virtual returns (string memory) {\\n return _name;\\n }\\n\\n /**\\n * @dev Returns the symbol of the token, usually a shorter version of the\\n * name.\\n */\\n function symbol() public view virtual returns (string memory) {\\n return _symbol;\\n }\\n\\n /**\\n * @dev Returns the number of decimals used to get its user representation.\\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\\n *\\n * Tokens usually opt for a value of 18, imitating the relationship between\\n * Ether and Wei. This is the default value returned by this function, unless\\n * it's overridden.\\n *\\n * NOTE: This information is only used for _display_ purposes: it in\\n * no way affects any of the arithmetic of the contract, including\\n * {IERC20-balanceOf} and {IERC20-transfer}.\\n */\\n function decimals() public view virtual returns (uint8) {\\n return 18;\\n }\\n\\n /**\\n * @dev See {IERC20-totalSupply}.\\n */\\n function totalSupply() public view virtual returns (uint256) {\\n return _totalSupply;\\n }\\n\\n /**\\n * @dev See {IERC20-balanceOf}.\\n */\\n function balanceOf(address account) public view virtual returns (uint256) {\\n return _balances[account];\\n }\\n\\n /**\\n * @dev See {IERC20-transfer}.\\n *\\n * Requirements:\\n *\\n * - `to` cannot be the zero address.\\n * - the caller must have a balance of at least `value`.\\n */\\n function transfer(address to, uint256 value) public virtual returns (bool) {\\n address owner = _msgSender();\\n _transfer(owner, to, value);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-allowance}.\\n */\\n function allowance(address owner, address spender) public view virtual returns (uint256) {\\n return _allowances[owner][spender];\\n }\\n\\n /**\\n * @dev See {IERC20-approve}.\\n *\\n * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\\n * `transferFrom`. This is semantically equivalent to an infinite approval.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n */\\n function approve(address spender, uint256 value) public virtual returns (bool) {\\n address owner = _msgSender();\\n _approve(owner, spender, value);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-transferFrom}.\\n *\\n * Emits an {Approval} event indicating the updated allowance. This is not\\n * required by the EIP. See the note at the beginning of {ERC20}.\\n *\\n * NOTE: Does not update the allowance if the current allowance\\n * is the maximum `uint256`.\\n *\\n * Requirements:\\n *\\n * - `from` and `to` cannot be the zero address.\\n * - `from` must have a balance of at least `value`.\\n * - the caller must have allowance for ``from``'s tokens of at least\\n * `value`.\\n */\\n function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\\n address spender = _msgSender();\\n _spendAllowance(from, spender, value);\\n _transfer(from, to, value);\\n return true;\\n }\\n\\n /**\\n * @dev Moves a `value` amount of tokens from `from` to `to`.\\n *\\n * This internal function is equivalent to {transfer}, and can be used to\\n * e.g. implement automatic token fees, slashing mechanisms, etc.\\n *\\n * Emits a {Transfer} event.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead.\\n */\\n function _transfer(address from, address to, uint256 value) internal {\\n if (from == address(0)) {\\n revert ERC20InvalidSender(address(0));\\n }\\n if (to == address(0)) {\\n revert ERC20InvalidReceiver(address(0));\\n }\\n _update(from, to, value);\\n }\\n\\n /**\\n * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\\n * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\\n * this function.\\n *\\n * Emits a {Transfer} event.\\n */\\n function _update(address from, address to, uint256 value) internal virtual {\\n if (from == address(0)) {\\n // Overflow check required: The rest of the code assumes that totalSupply never overflows\\n _totalSupply += value;\\n } else {\\n uint256 fromBalance = _balances[from];\\n if (fromBalance < value) {\\n revert ERC20InsufficientBalance(from, fromBalance, value);\\n }\\n unchecked {\\n // Overflow not possible: value <= fromBalance <= totalSupply.\\n _balances[from] = fromBalance - value;\\n }\\n }\\n\\n if (to == address(0)) {\\n unchecked {\\n // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\\n _totalSupply -= value;\\n }\\n } else {\\n unchecked {\\n // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\\n _balances[to] += value;\\n }\\n }\\n\\n emit Transfer(from, to, value);\\n }\\n\\n /**\\n * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\\n * Relies on the `_update` mechanism\\n *\\n * Emits a {Transfer} event with `from` set to the zero address.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead.\\n */\\n function _mint(address account, uint256 value) internal {\\n if (account == address(0)) {\\n revert ERC20InvalidReceiver(address(0));\\n }\\n _update(address(0), account, value);\\n }\\n\\n /**\\n * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\\n * Relies on the `_update` mechanism.\\n *\\n * Emits a {Transfer} event with `to` set to the zero address.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead\\n */\\n function _burn(address account, uint256 value) internal {\\n if (account == address(0)) {\\n revert ERC20InvalidSender(address(0));\\n }\\n _update(account, address(0), value);\\n }\\n\\n /**\\n * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\\n *\\n * This internal function is equivalent to `approve`, and can be used to\\n * e.g. set automatic allowances for certain subsystems, etc.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `owner` cannot be the zero address.\\n * - `spender` cannot be the zero address.\\n *\\n * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\\n */\\n function _approve(address owner, address spender, uint256 value) internal {\\n _approve(owner, spender, value, true);\\n }\\n\\n /**\\n * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\\n *\\n * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\\n * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\\n * `Approval` event during `transferFrom` operations.\\n *\\n * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\\n * true using the following override:\\n * ```\\n * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\\n * super._approve(owner, spender, value, true);\\n * }\\n * ```\\n *\\n * Requirements are the same as {_approve}.\\n */\\n function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\\n if (owner == address(0)) {\\n revert ERC20InvalidApprover(address(0));\\n }\\n if (spender == address(0)) {\\n revert ERC20InvalidSpender(address(0));\\n }\\n _allowances[owner][spender] = value;\\n if (emitEvent) {\\n emit Approval(owner, spender, value);\\n }\\n }\\n\\n /**\\n * @dev Updates `owner` s allowance for `spender` based on spent `value`.\\n *\\n * Does not update the allowance value in case of infinite allowance.\\n * Revert if not enough allowance is available.\\n *\\n * Does not emit an {Approval} event.\\n */\\n function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\\n uint256 currentAllowance = allowance(owner, spender);\\n if (currentAllowance != type(uint256).max) {\\n if (currentAllowance < value) {\\n revert ERC20InsufficientAllowance(spender, currentAllowance, value);\\n }\\n unchecked {\\n _approve(owner, spender, currentAllowance - value, false);\\n }\\n }\\n }\\n}\\n\",\"keccak256\":\"0xc3e1fa9d1987f8d349dfb4d6fe93bf2ca014b52ba335cfac30bfe71e357e6f80\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/IERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Interface of the ERC20 standard as defined in the EIP.\\n */\\ninterface IERC20 {\\n /**\\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\\n * another (`to`).\\n *\\n * Note that `value` may be zero.\\n */\\n event Transfer(address indexed from, address indexed to, uint256 value);\\n\\n /**\\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\\n * a call to {approve}. `value` is the new allowance.\\n */\\n event Approval(address indexed owner, address indexed spender, uint256 value);\\n\\n /**\\n * @dev Returns the value of tokens in existence.\\n */\\n function totalSupply() external view returns (uint256);\\n\\n /**\\n * @dev Returns the value of tokens owned by `account`.\\n */\\n function balanceOf(address account) external view returns (uint256);\\n\\n /**\\n * @dev Moves a `value` amount of tokens from the caller's account to `to`.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transfer(address to, uint256 value) external returns (bool);\\n\\n /**\\n * @dev Returns the remaining number of tokens that `spender` will be\\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\\n * zero by default.\\n *\\n * This value changes when {approve} or {transferFrom} are called.\\n */\\n function allowance(address owner, address spender) external view returns (uint256);\\n\\n /**\\n * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\\n * caller's tokens.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\\n * that someone may use both the old and the new allowance by unfortunate\\n * transaction ordering. One possible solution to mitigate this race\\n * condition is to first reduce the spender's allowance to 0 and set the\\n * desired value afterwards:\\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\\n *\\n * Emits an {Approval} event.\\n */\\n function approve(address spender, uint256 value) external returns (bool);\\n\\n /**\\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\\n * allowance mechanism. `value` is then deducted from the caller's\\n * allowance.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transferFrom(address from, address to, uint256 value) external returns (bool);\\n}\\n\",\"keccak256\":\"0xc6a8ff0ea489379b61faa647490411b80102578440ab9d84e9a957cc12164e70\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20, IERC20Metadata, ERC20} from \\\"../ERC20.sol\\\";\\nimport {SafeERC20} from \\\"../utils/SafeERC20.sol\\\";\\nimport {IERC4626} from \\\"../../../interfaces/IERC4626.sol\\\";\\nimport {Math} from \\\"../../../utils/math/Math.sol\\\";\\n\\n/**\\n * @dev Implementation of the ERC4626 \\\"Tokenized Vault Standard\\\" as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].\\n *\\n * This extension allows the minting and burning of \\\"shares\\\" (represented using the ERC20 inheritance) in exchange for\\n * underlying \\\"assets\\\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\\n * the ERC20 standard. Any additional extensions included along it would affect the \\\"shares\\\" token represented by this\\n * contract and not the \\\"assets\\\" token which is an independent contract.\\n *\\n * [CAUTION]\\n * ====\\n * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning\\n * with a \\\"donation\\\" to the vault that inflates the price of a share. This is variously known as a donation or inflation\\n * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial\\n * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may\\n * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by\\n * verifying the amount received is as expected, using a wrapper that performs these checks such as\\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\\n *\\n * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`\\n * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault\\n * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself\\n * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset\\n * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's\\n * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more\\n * expensive than it is profitable. More details about the underlying math can be found\\n * xref:erc4626.adoc#inflation-attack[here].\\n *\\n * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued\\n * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets\\n * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience\\n * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the\\n * `_convertToShares` and `_convertToAssets` functions.\\n *\\n * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].\\n * ====\\n */\\nabstract contract ERC4626 is ERC20, IERC4626 {\\n using Math for uint256;\\n\\n IERC20 private immutable _asset;\\n uint8 private immutable _underlyingDecimals;\\n\\n /**\\n * @dev Attempted to deposit more assets than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);\\n\\n /**\\n * @dev Attempted to mint more shares than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);\\n\\n /**\\n * @dev Attempted to withdraw more assets than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);\\n\\n /**\\n * @dev Attempted to redeem more shares than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);\\n\\n /**\\n * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).\\n */\\n constructor(IERC20 asset_) {\\n (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\\n _underlyingDecimals = success ? assetDecimals : 18;\\n _asset = asset_;\\n }\\n\\n /**\\n * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\\n */\\n function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {\\n (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(\\n abi.encodeCall(IERC20Metadata.decimals, ())\\n );\\n if (success && encodedDecimals.length >= 32) {\\n uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));\\n if (returnedDecimals <= type(uint8).max) {\\n return (true, uint8(returnedDecimals));\\n }\\n }\\n return (false, 0);\\n }\\n\\n /**\\n * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This\\n * \\\"original\\\" value is cached during construction of the vault contract. If this read operation fails (e.g., the\\n * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.\\n *\\n * See {IERC20Metadata-decimals}.\\n */\\n function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {\\n return _underlyingDecimals + _decimalsOffset();\\n }\\n\\n /** @dev See {IERC4626-asset}. */\\n function asset() public view virtual returns (address) {\\n return address(_asset);\\n }\\n\\n /** @dev See {IERC4626-totalAssets}. */\\n function totalAssets() public view virtual returns (uint256) {\\n return _asset.balanceOf(address(this));\\n }\\n\\n /** @dev See {IERC4626-convertToShares}. */\\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-convertToAssets}. */\\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-maxDeposit}. */\\n function maxDeposit(address) public view virtual returns (uint256) {\\n return type(uint256).max;\\n }\\n\\n /** @dev See {IERC4626-maxMint}. */\\n function maxMint(address) public view virtual returns (uint256) {\\n return type(uint256).max;\\n }\\n\\n /** @dev See {IERC4626-maxWithdraw}. */\\n function maxWithdraw(address owner) public view virtual returns (uint256) {\\n return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-maxRedeem}. */\\n function maxRedeem(address owner) public view virtual returns (uint256) {\\n return balanceOf(owner);\\n }\\n\\n /** @dev See {IERC4626-previewDeposit}. */\\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-previewMint}. */\\n function previewMint(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Ceil);\\n }\\n\\n /** @dev See {IERC4626-previewWithdraw}. */\\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Ceil);\\n }\\n\\n /** @dev See {IERC4626-previewRedeem}. */\\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-deposit}. */\\n function deposit(uint256 assets, address receiver) public virtual returns (uint256) {\\n uint256 maxAssets = maxDeposit(receiver);\\n if (assets > maxAssets) {\\n revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);\\n }\\n\\n uint256 shares = previewDeposit(assets);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-mint}.\\n *\\n * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.\\n * In this case, the shares will be minted without requiring any assets to be deposited.\\n */\\n function mint(uint256 shares, address receiver) public virtual returns (uint256) {\\n uint256 maxShares = maxMint(receiver);\\n if (shares > maxShares) {\\n revert ERC4626ExceededMaxMint(receiver, shares, maxShares);\\n }\\n\\n uint256 assets = previewMint(shares);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return assets;\\n }\\n\\n /** @dev See {IERC4626-withdraw}. */\\n function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {\\n uint256 maxAssets = maxWithdraw(owner);\\n if (assets > maxAssets) {\\n revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);\\n }\\n\\n uint256 shares = previewWithdraw(assets);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-redeem}. */\\n function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {\\n uint256 maxShares = maxRedeem(owner);\\n if (shares > maxShares) {\\n revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);\\n }\\n\\n uint256 assets = previewRedeem(shares);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return assets;\\n }\\n\\n /**\\n * @dev Internal conversion function (from assets to shares) with support for rounding direction.\\n */\\n function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {\\n return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);\\n }\\n\\n /**\\n * @dev Internal conversion function (from shares to assets) with support for rounding direction.\\n */\\n function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {\\n return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);\\n }\\n\\n /**\\n * @dev Deposit/mint common workflow.\\n */\\n function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {\\n // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the\\n // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\\n // assets are transferred and before the shares are minted, which is a valid state.\\n // slither-disable-next-line reentrancy-no-eth\\n SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);\\n _mint(receiver, shares);\\n\\n emit Deposit(caller, receiver, assets, shares);\\n }\\n\\n /**\\n * @dev Withdraw/redeem common workflow.\\n */\\n function _withdraw(\\n address caller,\\n address receiver,\\n address owner,\\n uint256 assets,\\n uint256 shares\\n ) internal virtual {\\n if (caller != owner) {\\n _spendAllowance(owner, caller, shares);\\n }\\n\\n // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\\n // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\\n // shares are burned and after the assets are transferred, which is a valid state.\\n _burn(owner, shares);\\n SafeERC20.safeTransfer(_asset, receiver, assets);\\n\\n emit Withdraw(caller, receiver, owner, assets, shares);\\n }\\n\\n function _decimalsOffset() internal view virtual returns (uint8) {\\n return 0;\\n }\\n}\\n\",\"keccak256\":\"0x1837547e04d5fe5334eeb77a345683c22995f1e7aa033020757ddf83a80fc72d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../IERC20.sol\\\";\\n\\n/**\\n * @dev Interface for the optional metadata functions from the ERC20 standard.\\n */\\ninterface IERC20Metadata is IERC20 {\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() external view returns (string memory);\\n\\n /**\\n * @dev Returns the symbol of the token.\\n */\\n function symbol() external view returns (string memory);\\n\\n /**\\n * @dev Returns the decimals places of the token.\\n */\\n function decimals() external view returns (uint8);\\n}\\n\",\"keccak256\":\"0xaa761817f6cd7892fcf158b3c776b34551cde36f48ff9703d53898bc45a94ea2\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\\n *\\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\\n * need to send a transaction, and thus is not required to hold Ether at all.\\n *\\n * ==== Security Considerations\\n *\\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\\n * generally recommended is:\\n *\\n * ```solidity\\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\\n * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\\n * doThing(..., value);\\n * }\\n *\\n * function doThing(..., uint256 value) public {\\n * token.safeTransferFrom(msg.sender, address(this), value);\\n * ...\\n * }\\n * ```\\n *\\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\\n * {SafeERC20-safeTransferFrom}).\\n *\\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\\n * contracts should have entry points that don't rely on permit.\\n */\\ninterface IERC20Permit {\\n /**\\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\\n * given ``owner``'s signed approval.\\n *\\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\\n * ordering also apply here.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n * - `deadline` must be a timestamp in the future.\\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\\n * over the EIP712-formatted function arguments.\\n * - the signature must use ``owner``'s current nonce (see {nonces}).\\n *\\n * For more information on the signature format, see the\\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\\n * section].\\n *\\n * CAUTION: See Security Considerations above.\\n */\\n function permit(\\n address owner,\\n address spender,\\n uint256 value,\\n uint256 deadline,\\n uint8 v,\\n bytes32 r,\\n bytes32 s\\n ) external;\\n\\n /**\\n * @dev Returns the current nonce for `owner`. This value must be\\n * included whenever a signature is generated for {permit}.\\n *\\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\\n * prevents a signature from being used multiple times.\\n */\\n function nonces(address owner) external view returns (uint256);\\n\\n /**\\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\\n */\\n // solhint-disable-next-line func-name-mixedcase\\n function DOMAIN_SEPARATOR() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0x6008dabfe393240d73d7dd7688033f72740d570aa422254d29a7dce8568f3aff\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../IERC20.sol\\\";\\nimport {IERC20Permit} from \\\"../extensions/IERC20Permit.sol\\\";\\nimport {Address} from \\\"../../../utils/Address.sol\\\";\\n\\n/**\\n * @title SafeERC20\\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\\n * contract returns false). Tokens that return no value (and instead revert or\\n * throw on failure) are also supported, non-reverting calls are assumed to be\\n * successful.\\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\\n */\\nlibrary SafeERC20 {\\n using Address for address;\\n\\n /**\\n * @dev An operation with an ERC20 token failed.\\n */\\n error SafeERC20FailedOperation(address token);\\n\\n /**\\n * @dev Indicates a failed `decreaseAllowance` request.\\n */\\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\\n\\n /**\\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful.\\n */\\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\\n }\\n\\n /**\\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\\n */\\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\\n }\\n\\n /**\\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful.\\n */\\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\\n uint256 oldAllowance = token.allowance(address(this), spender);\\n forceApprove(token, spender, oldAllowance + value);\\n }\\n\\n /**\\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\\n * value, non-reverting calls are assumed to be successful.\\n */\\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\\n unchecked {\\n uint256 currentAllowance = token.allowance(address(this), spender);\\n if (currentAllowance < requestedDecrease) {\\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\\n }\\n forceApprove(token, spender, currentAllowance - requestedDecrease);\\n }\\n }\\n\\n /**\\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\\n * to be set to zero before setting it to a non-zero value, such as USDT.\\n */\\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\\n\\n if (!_callOptionalReturnBool(token, approvalCall)) {\\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\\n _callOptionalReturn(token, approvalCall);\\n }\\n }\\n\\n /**\\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\\n * on the return value: the return value is optional (but if data is returned, it must not be false).\\n * @param token The token targeted by the call.\\n * @param data The call data (encoded using abi.encode or one of its variants).\\n */\\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\\n // the target address contains contract code and also asserts for success in the low-level call.\\n\\n bytes memory returndata = address(token).functionCall(data);\\n if (returndata.length != 0 && !abi.decode(returndata, (bool))) {\\n revert SafeERC20FailedOperation(address(token));\\n }\\n }\\n\\n /**\\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\\n * on the return value: the return value is optional (but if data is returned, it must not be false).\\n * @param token The token targeted by the call.\\n * @param data The call data (encoded using abi.encode or one of its variants).\\n *\\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\\n */\\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\\n // and not revert is the subcall reverts.\\n\\n (bool success, bytes memory returndata) = address(token).call(data);\\n return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;\\n }\\n}\\n\",\"keccak256\":\"0x37bb49513c49c87c4642a891b13b63571bc87013dde806617aa1efb54605f386\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Address.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary Address {\\n /**\\n * @dev The ETH balance of the account is not enough to perform the operation.\\n */\\n error AddressInsufficientBalance(address account);\\n\\n /**\\n * @dev There's no code at `target` (it is not a contract).\\n */\\n error AddressEmptyCode(address target);\\n\\n /**\\n * @dev A call to an address target failed. The target may have reverted.\\n */\\n error FailedInnerCall();\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n if (address(this).balance < amount) {\\n revert AddressInsufficientBalance(address(this));\\n }\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n if (!success) {\\n revert FailedInnerCall();\\n }\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason or custom error, it is bubbled\\n * up by this function (like regular Solidity function calls). However, if\\n * the call reverted with no returned reason, this function reverts with a\\n * {FailedInnerCall} error.\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n */\\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\\n if (address(this).balance < value) {\\n revert AddressInsufficientBalance(address(this));\\n }\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a delegate call.\\n */\\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.delegatecall(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\\n * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\\n * unsuccessful call.\\n */\\n function verifyCallResultFromTarget(\\n address target,\\n bool success,\\n bytes memory returndata\\n ) internal view returns (bytes memory) {\\n if (!success) {\\n _revert(returndata);\\n } else {\\n // only check if target is a contract if the call was successful and the return data is empty\\n // otherwise we already know that it was a contract\\n if (returndata.length == 0 && target.code.length == 0) {\\n revert AddressEmptyCode(target);\\n }\\n return returndata;\\n }\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\\n * revert reason or with a default {FailedInnerCall} error.\\n */\\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\\n if (!success) {\\n _revert(returndata);\\n } else {\\n return returndata;\\n }\\n }\\n\\n /**\\n * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\\n */\\n function _revert(bytes memory returndata) private pure {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n /// @solidity memory-safe-assembly\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert FailedInnerCall();\\n }\\n }\\n}\\n\",\"keccak256\":\"0xaf28a975a78550e45f65e559a3ad6a5ad43b9b8a37366999abd1b7084eb70721\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Context.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Provides information about the current execution context, including the\\n * sender of the transaction and its data. While these are generally available\\n * via msg.sender and msg.data, they should not be accessed in such a direct\\n * manner, since when dealing with meta-transactions the account sending and\\n * paying for execution may not be the actual sender (as far as an application\\n * is concerned).\\n *\\n * This contract is only required for intermediate, library-like contracts.\\n */\\nabstract contract Context {\\n function _msgSender() internal view virtual returns (address) {\\n return msg.sender;\\n }\\n\\n function _msgData() internal view virtual returns (bytes calldata) {\\n return msg.data;\\n }\\n}\\n\",\"keccak256\":\"0x75a4ee64c68dbd5f38bddd06e664a64c8271b4caa554fb6f0607dfd672bb4bf3\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/math/Math.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Standard math utilities missing in the Solidity language.\\n */\\nlibrary Math {\\n /**\\n * @dev Muldiv operation overflow.\\n */\\n error MathOverflowedMulDiv();\\n\\n enum Rounding {\\n Floor, // Toward negative infinity\\n Ceil, // Toward positive infinity\\n Trunc, // Toward zero\\n Expand // Away from zero\\n }\\n\\n /**\\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\\n */\\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n uint256 c = a + b;\\n if (c < a) return (false, 0);\\n return (true, c);\\n }\\n }\\n\\n /**\\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\\n */\\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b > a) return (false, 0);\\n return (true, a - b);\\n }\\n }\\n\\n /**\\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\\n */\\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\\n // benefit is lost if 'b' is also tested.\\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\\n if (a == 0) return (true, 0);\\n uint256 c = a * b;\\n if (c / a != b) return (false, 0);\\n return (true, c);\\n }\\n }\\n\\n /**\\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\\n */\\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b == 0) return (false, 0);\\n return (true, a / b);\\n }\\n }\\n\\n /**\\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\\n */\\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b == 0) return (false, 0);\\n return (true, a % b);\\n }\\n }\\n\\n /**\\n * @dev Returns the largest of two numbers.\\n */\\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a > b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the smallest of two numbers.\\n */\\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a < b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the average of two numbers. The result is rounded towards\\n * zero.\\n */\\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\\n // (a + b) / 2 can overflow.\\n return (a & b) + (a ^ b) / 2;\\n }\\n\\n /**\\n * @dev Returns the ceiling of the division of two numbers.\\n *\\n * This differs from standard division with `/` in that it rounds towards infinity instead\\n * of rounding towards zero.\\n */\\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\\n if (b == 0) {\\n // Guarantee the same behavior as in a regular Solidity division.\\n return a / b;\\n }\\n\\n // (a + b - 1) / b can overflow on addition, so we distribute.\\n return a == 0 ? 0 : (a - 1) / b + 1;\\n }\\n\\n /**\\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\\n * denominator == 0.\\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\\n * Uniswap Labs also under MIT license.\\n */\\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\\n unchecked {\\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\\n // variables such that product = prod1 * 2^256 + prod0.\\n uint256 prod0 = x * y; // Least significant 256 bits of the product\\n uint256 prod1; // Most significant 256 bits of the product\\n assembly {\\n let mm := mulmod(x, y, not(0))\\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\\n }\\n\\n // Handle non-overflow cases, 256 by 256 division.\\n if (prod1 == 0) {\\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\\n // The surrounding unchecked block does not change this fact.\\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\\n return prod0 / denominator;\\n }\\n\\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\\n if (denominator <= prod1) {\\n revert MathOverflowedMulDiv();\\n }\\n\\n ///////////////////////////////////////////////\\n // 512 by 256 division.\\n ///////////////////////////////////////////////\\n\\n // Make division exact by subtracting the remainder from [prod1 prod0].\\n uint256 remainder;\\n assembly {\\n // Compute remainder using mulmod.\\n remainder := mulmod(x, y, denominator)\\n\\n // Subtract 256 bit number from 512 bit number.\\n prod1 := sub(prod1, gt(remainder, prod0))\\n prod0 := sub(prod0, remainder)\\n }\\n\\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\\n\\n uint256 twos = denominator & (0 - denominator);\\n assembly {\\n // Divide denominator by twos.\\n denominator := div(denominator, twos)\\n\\n // Divide [prod1 prod0] by twos.\\n prod0 := div(prod0, twos)\\n\\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\\n twos := add(div(sub(0, twos), twos), 1)\\n }\\n\\n // Shift in bits from prod1 into prod0.\\n prod0 |= prod1 * twos;\\n\\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\\n // four bits. That is, denominator * inv = 1 mod 2^4.\\n uint256 inverse = (3 * denominator) ^ 2;\\n\\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\\n // works in modular arithmetic, doubling the correct bits in each step.\\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\\n\\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\\n // is no longer required.\\n result = prod0 * inverse;\\n return result;\\n }\\n }\\n\\n /**\\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\\n */\\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\\n uint256 result = mulDiv(x, y, denominator);\\n if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\\n result += 1;\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\\n * towards zero.\\n *\\n * Inspired by Henry S. Warren, Jr.'s \\\"Hacker's Delight\\\" (Chapter 11).\\n */\\n function sqrt(uint256 a) internal pure returns (uint256) {\\n if (a == 0) {\\n return 0;\\n }\\n\\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\\n //\\n // We know that the \\\"msb\\\" (most significant bit) of our target number `a` is a power of 2 such that we have\\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\\n //\\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\\n // \\u2192 `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\\n // \\u2192 `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\\n //\\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\\n uint256 result = 1 << (log2(a) >> 1);\\n\\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\\n // into the expected uint128 result.\\n unchecked {\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n return min(result, a / result);\\n }\\n }\\n\\n /**\\n * @notice Calculates sqrt(a), following the selected rounding direction.\\n */\\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = sqrt(a);\\n return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 2 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 128;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 64;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 32;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 16;\\n }\\n if (value >> 8 > 0) {\\n value >>= 8;\\n result += 8;\\n }\\n if (value >> 4 > 0) {\\n value >>= 4;\\n result += 4;\\n }\\n if (value >> 2 > 0) {\\n value >>= 2;\\n result += 2;\\n }\\n if (value >> 1 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log2(value);\\n return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 10 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >= 10 ** 64) {\\n value /= 10 ** 64;\\n result += 64;\\n }\\n if (value >= 10 ** 32) {\\n value /= 10 ** 32;\\n result += 32;\\n }\\n if (value >= 10 ** 16) {\\n value /= 10 ** 16;\\n result += 16;\\n }\\n if (value >= 10 ** 8) {\\n value /= 10 ** 8;\\n result += 8;\\n }\\n if (value >= 10 ** 4) {\\n value /= 10 ** 4;\\n result += 4;\\n }\\n if (value >= 10 ** 2) {\\n value /= 10 ** 2;\\n result += 2;\\n }\\n if (value >= 10 ** 1) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log10(value);\\n return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 256 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n *\\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\\n */\\n function log256(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 16;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 8;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 4;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 2;\\n }\\n if (value >> 8 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log256(value);\\n return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\\n */\\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\\n return uint8(rounding) % 2 == 1;\\n }\\n}\\n\",\"keccak256\":\"0x005ec64c6313f0555d59e278f9a7a5ab2db5bdc72a027f255a37c327af1ec02d\",\"license\":\"MIT\"},\"contracts/Dispatcher.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/access/Ownable.sol\\\";\\nimport \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport \\\"@openzeppelin/contracts/interfaces/IERC4626.sol\\\";\\nimport \\\"./Router.sol\\\";\\nimport \\\"./stBTC.sol\\\";\\n\\n/// @title Dispatcher\\n/// @notice Dispatcher is a contract that routes tBTC from stBTC to\\n/// yield vaults and back. Vaults supply yield strategies with tBTC that\\n/// generate yield for Bitcoin holders.\\ncontract Dispatcher is Router, Ownable {\\n using SafeERC20 for IERC20;\\n\\n /// Struct holds information about a vault.\\n struct VaultInfo {\\n bool authorized;\\n }\\n\\n /// The main stBTC contract holding tBTC deposited by stakers.\\n stBTC public immutable stbtc;\\n /// tBTC token contract.\\n IERC20 public immutable tbtc;\\n /// Address of the maintainer bot.\\n address public maintainer;\\n\\n /// Authorized Yield Vaults that implement ERC4626 standard. These\\n /// vaults deposit assets to yield strategies, e.g. Uniswap V3\\n /// WBTC/TBTC pool. Vault can be a part of Acre ecosystem or can be\\n /// implemented externally. As long as it complies with ERC4626\\n /// standard and is authorized by the owner it can be plugged into\\n /// Acre.\\n address[] public vaults;\\n /// Mapping of vaults to their information.\\n mapping(address => VaultInfo) public vaultsInfo;\\n\\n /// Emitted when a vault is authorized.\\n /// @param vault Address of the vault.\\n event VaultAuthorized(address indexed vault);\\n\\n /// Emitted when a vault is deauthorized.\\n /// @param vault Address of the vault.\\n event VaultDeauthorized(address indexed vault);\\n\\n /// Emitted when tBTC is routed to a vault.\\n /// @param vault Address of the vault.\\n /// @param amount Amount of tBTC.\\n /// @param sharesOut Amount of received shares.\\n event DepositAllocated(\\n address indexed vault,\\n uint256 amount,\\n uint256 sharesOut\\n );\\n\\n /// Emitted when the maintainer address is updated.\\n /// @param maintainer Address of the new maintainer.\\n event MaintainerUpdated(address indexed maintainer);\\n\\n /// Reverts if the vault is already authorized.\\n error VaultAlreadyAuthorized();\\n\\n /// Reverts if the vault is not authorized.\\n error VaultUnauthorized();\\n\\n /// Reverts if the caller is not the maintainer.\\n error NotMaintainer();\\n\\n /// Reverts if the address is zero.\\n error ZeroAddress();\\n\\n /// Modifier that reverts if the caller is not the maintainer.\\n modifier onlyMaintainer() {\\n if (msg.sender != maintainer) {\\n revert NotMaintainer();\\n }\\n _;\\n }\\n\\n constructor(stBTC _stbtc, IERC20 _tbtc) Ownable(msg.sender) {\\n stbtc = _stbtc;\\n tbtc = _tbtc;\\n }\\n\\n /// @notice Adds a vault to the list of authorized vaults.\\n /// @param vault Address of the vault to add.\\n function authorizeVault(address vault) external onlyOwner {\\n if (isVaultAuthorized(vault)) {\\n revert VaultAlreadyAuthorized();\\n }\\n\\n vaults.push(vault);\\n vaultsInfo[vault].authorized = true;\\n\\n emit VaultAuthorized(vault);\\n }\\n\\n /// @notice Removes a vault from the list of authorized vaults.\\n /// @param vault Address of the vault to remove.\\n function deauthorizeVault(address vault) external onlyOwner {\\n if (!isVaultAuthorized(vault)) {\\n revert VaultUnauthorized();\\n }\\n\\n vaultsInfo[vault].authorized = false;\\n\\n for (uint256 i = 0; i < vaults.length; i++) {\\n if (vaults[i] == vault) {\\n vaults[i] = vaults[vaults.length - 1];\\n // slither-disable-next-line costly-loop\\n vaults.pop();\\n break;\\n }\\n }\\n\\n emit VaultDeauthorized(vault);\\n }\\n\\n /// @notice Updates the maintainer address.\\n /// @param newMaintainer Address of the new maintainer.\\n function updateMaintainer(address newMaintainer) external onlyOwner {\\n if (newMaintainer == address(0)) {\\n revert ZeroAddress();\\n }\\n\\n maintainer = newMaintainer;\\n\\n emit MaintainerUpdated(maintainer);\\n }\\n\\n /// TODO: make this function internal once the allocation distribution is\\n /// implemented\\n /// @notice Routes tBTC from stBTC to a vault. Can be called by the maintainer\\n /// only.\\n /// @param vault Address of the vault to route the assets to.\\n /// @param amount Amount of tBTC to deposit.\\n /// @param minSharesOut Minimum amount of shares to receive.\\n function depositToVault(\\n address vault,\\n uint256 amount,\\n uint256 minSharesOut\\n ) public onlyMaintainer {\\n if (!isVaultAuthorized(vault)) {\\n revert VaultUnauthorized();\\n }\\n\\n // slither-disable-next-line arbitrary-send-erc20\\n tbtc.safeTransferFrom(address(stbtc), address(this), amount);\\n tbtc.forceApprove(address(vault), amount);\\n\\n uint256 sharesOut = deposit(\\n IERC4626(vault),\\n address(stbtc),\\n amount,\\n minSharesOut\\n );\\n // slither-disable-next-line reentrancy-events\\n emit DepositAllocated(vault, amount, sharesOut);\\n }\\n\\n /// @notice Returns the list of authorized vaults.\\n function getVaults() public view returns (address[] memory) {\\n return vaults;\\n }\\n\\n /// @notice Returns true if the vault is authorized.\\n /// @param vault Address of the vault to check.\\n function isVaultAuthorized(address vault) public view returns (bool) {\\n return vaultsInfo[vault].authorized;\\n }\\n\\n /// TODO: implement redeem() / withdraw() functions\\n}\\n\",\"keccak256\":\"0x0dd77692ab8c6059afa7b4a90f26733560b53fb66192e9912a2064103c5d41fb\",\"license\":\"GPL-3.0-only\"},\"contracts/Router.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/interfaces/IERC4626.sol\\\";\\n\\n/// @title Router\\n/// @notice Router is a contract that routes tBTC from stBTC to\\n/// a given vault and back. Vaults supply yield strategies with tBTC that\\n/// generate yield for Bitcoin holders.\\nabstract contract Router {\\n /// Thrown when amount of shares received is below the min set by caller.\\n /// @param vault Address of the vault.\\n /// @param sharesOut Amount of received shares.\\n /// @param minSharesOut Minimum amount of shares expected to receive.\\n error MinSharesError(\\n address vault,\\n uint256 sharesOut,\\n uint256 minSharesOut\\n );\\n\\n /// @notice Routes funds from stBTC to a vault. The amount of tBTC to\\n /// Shares of deposited tBTC are minted to the stBTC contract.\\n /// @param vault Address of the vault to route the funds to.\\n /// @param receiver Address of the receiver of the shares.\\n /// @param amount Amount of tBTC to deposit.\\n /// @param minSharesOut Minimum amount of shares to receive.\\n function deposit(\\n IERC4626 vault,\\n address receiver,\\n uint256 amount,\\n uint256 minSharesOut\\n ) internal returns (uint256 sharesOut) {\\n if ((sharesOut = vault.deposit(amount, receiver)) < minSharesOut) {\\n revert MinSharesError(address(vault), sharesOut, minSharesOut);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x520e27c613f1234755c23402524b048a81abd15222d7f318504992d490248812\",\"license\":\"GPL-3.0-only\"},\"contracts/lib/ERC4626Fees.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n\\n// Inspired by https://docs.openzeppelin.com/contracts/5.x/erc4626#fees\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"@openzeppelin/contracts/token/ERC20/IERC20.sol\\\";\\nimport {ERC4626} from \\\"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\\\";\\nimport {SafeERC20} from \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport {Math} from \\\"@openzeppelin/contracts/utils/math/Math.sol\\\";\\n\\n/// @dev ERC4626 vault with entry/exit fees expressed in https://en.wikipedia.org/wiki/Basis_point[basis point (bp)].\\nabstract contract ERC4626Fees is ERC4626 {\\n using Math for uint256;\\n\\n uint256 private constant _BASIS_POINT_SCALE = 1e4;\\n\\n // === Overrides ===\\n\\n /// @dev Preview taking an entry fee on deposit. See {IERC4626-previewDeposit}.\\n function previewDeposit(\\n uint256 assets\\n ) public view virtual override returns (uint256) {\\n uint256 fee = _feeOnTotal(assets, _entryFeeBasisPoints());\\n return super.previewDeposit(assets - fee);\\n }\\n\\n /// @dev Preview adding an entry fee on mint. See {IERC4626-previewMint}.\\n function previewMint(\\n uint256 shares\\n ) public view virtual override returns (uint256) {\\n uint256 assets = super.previewMint(shares);\\n return assets + _feeOnRaw(assets, _entryFeeBasisPoints());\\n }\\n\\n // TODO: add previewWithraw\\n\\n // TODO: add previewRedeem\\n\\n /// @dev Send entry fee to {_feeRecipient}. See {IERC4626-_deposit}.\\n function _deposit(\\n address caller,\\n address receiver,\\n uint256 assets,\\n uint256 shares\\n ) internal virtual override {\\n uint256 fee = _feeOnTotal(assets, _entryFeeBasisPoints());\\n address recipient = _feeRecipient();\\n\\n super._deposit(caller, receiver, assets, shares);\\n\\n if (fee > 0 && recipient != address(this)) {\\n SafeERC20.safeTransfer(IERC20(asset()), recipient, fee);\\n }\\n }\\n\\n // TODO: add withdraw\\n\\n // === Fee configuration ===\\n\\n // slither-disable-next-line dead-code\\n function _entryFeeBasisPoints() internal view virtual returns (uint256);\\n\\n // TODO: add exitFeeBasisPoints\\n\\n // slither-disable-next-line dead-code\\n function _feeRecipient() internal view virtual returns (address);\\n\\n // === Fee operations ===\\n\\n /// @dev Calculates the fees that should be added to an amount `assets`\\n /// that does not already include fees.\\n /// Used in {IERC4626-mint} and {IERC4626-withdraw} operations.\\n function _feeOnRaw(\\n uint256 assets,\\n uint256 feeBasisPoints\\n ) private pure returns (uint256) {\\n return\\n assets.mulDiv(\\n feeBasisPoints,\\n _BASIS_POINT_SCALE,\\n Math.Rounding.Ceil\\n );\\n }\\n\\n /// @dev Calculates the fee part of an amount `assets` that already includes fees.\\n /// Used in {IERC4626-deposit} and {IERC4626-redeem} operations.\\n function _feeOnTotal(\\n uint256 assets,\\n uint256 feeBasisPoints\\n ) private pure returns (uint256) {\\n return\\n assets.mulDiv(\\n feeBasisPoints,\\n feeBasisPoints + _BASIS_POINT_SCALE,\\n Math.Rounding.Ceil\\n );\\n }\\n}\\n\",\"keccak256\":\"0xccfc01be23cbc979745a6e7f3421c4d050dc2ad7ddb6d9e1543c8e681e91d596\",\"license\":\"MIT\"},\"contracts/stBTC.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\\\";\\nimport \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport \\\"@openzeppelin/contracts/access/Ownable.sol\\\";\\nimport \\\"./Dispatcher.sol\\\";\\nimport \\\"./lib/ERC4626Fees.sol\\\";\\n\\n/// @title stBTC\\n/// @notice This contract implements the ERC-4626 tokenized vault standard. By\\n/// staking tBTC, users acquire a liquid staking token called stBTC,\\n/// commonly referred to as \\\"shares\\\". The staked tBTC is securely\\n/// deposited into Acre's vaults, where it generates yield over time.\\n/// Users have the flexibility to redeem stBTC, enabling them to\\n/// withdraw their staked tBTC along with the accrued yield.\\n/// @dev ERC-4626 is a standard to optimize and unify the technical parameters\\n/// of yield-bearing vaults. This contract facilitates the minting and\\n/// burning of shares (stBTC), which are represented as standard ERC20\\n/// tokens, providing a seamless exchange with tBTC tokens.\\ncontract stBTC is ERC4626Fees, Ownable {\\n using SafeERC20 for IERC20;\\n\\n /// Dispatcher contract that routes tBTC from stBTC to a given vault and back.\\n Dispatcher public dispatcher;\\n\\n /// Address of the treasury wallet, where fees should be transferred to.\\n address public treasury;\\n\\n /// Entry fee basis points applied to entry fee calculation.\\n uint256 public entryFeeBasisPoints;\\n\\n /// Minimum amount for a single deposit operation. The value should be set\\n /// low enough so the deposits routed through TbtcDepositor contract won't\\n /// be rejected. It means that minimumDepositAmount should be lower than\\n /// tBTC protocol's depositDustThreshold reduced by all the minting fees taken\\n /// before depositing in the Acre contract.\\n uint256 public minimumDepositAmount;\\n\\n /// Maximum total amount of tBTC token held by Acre protocol.\\n uint256 public maximumTotalAssets;\\n\\n /// Emitted when a referral is used.\\n /// @param referral Used for referral program.\\n /// @param assets Amount of tBTC tokens staked.\\n event StakeReferral(uint16 indexed referral, uint256 assets);\\n\\n /// Emitted when the treasury wallet address is updated.\\n /// @param treasury New treasury wallet address.\\n event TreasuryUpdated(address treasury);\\n\\n /// Emitted when deposit parameters are updated.\\n /// @param minimumDepositAmount New value of the minimum deposit amount.\\n /// @param maximumTotalAssets New value of the maximum total assets amount.\\n event DepositParametersUpdated(\\n uint256 minimumDepositAmount,\\n uint256 maximumTotalAssets\\n );\\n\\n /// Emitted when the dispatcher contract is updated.\\n /// @param oldDispatcher Address of the old dispatcher contract.\\n /// @param newDispatcher Address of the new dispatcher contract.\\n event DispatcherUpdated(address oldDispatcher, address newDispatcher);\\n\\n /// Emitted when the entry fee basis points are updated.\\n /// @param entryFeeBasisPoints New value of the fee basis points.\\n event EntryFeeBasisPointsUpdated(uint256 entryFeeBasisPoints);\\n\\n /// Reverts if the amount is less than the minimum deposit amount.\\n /// @param amount Amount to check.\\n /// @param min Minimum amount to check 'amount' against.\\n error LessThanMinDeposit(uint256 amount, uint256 min);\\n\\n /// Reverts if the address is zero.\\n error ZeroAddress();\\n\\n /// Reverts if the address is disallowed.\\n error DisallowedAddress();\\n\\n constructor(\\n IERC20 _tbtc,\\n address _treasury\\n ) ERC4626(_tbtc) ERC20(\\\"Acre Staked Bitcoin\\\", \\\"stBTC\\\") Ownable(msg.sender) {\\n if (address(_treasury) == address(0)) {\\n revert ZeroAddress();\\n }\\n treasury = _treasury;\\n // TODO: Revisit the exact values closer to the launch.\\n minimumDepositAmount = 0.001 * 1e18; // 0.001 tBTC\\n maximumTotalAssets = 25 * 1e18; // 25 tBTC\\n entryFeeBasisPoints = 5; // 5bps == 0.05% == 0.0005\\n }\\n\\n /// @notice Updates treasury wallet address.\\n /// @param newTreasury New treasury wallet address.\\n function updateTreasury(address newTreasury) external onlyOwner {\\n // TODO: Introduce a parameters update process.\\n if (newTreasury == address(0)) {\\n revert ZeroAddress();\\n }\\n if (newTreasury == address(this)) {\\n revert DisallowedAddress();\\n }\\n treasury = newTreasury;\\n\\n emit TreasuryUpdated(newTreasury);\\n }\\n\\n /// @notice Updates deposit parameters.\\n /// @dev To disable the limit for deposits, set the maximum total assets to\\n /// maximum (`type(uint256).max`).\\n /// @param _minimumDepositAmount New value of the minimum deposit amount. It\\n /// is the minimum amount for a single deposit operation.\\n /// @param _maximumTotalAssets New value of the maximum total assets amount.\\n /// It is the maximum amount of the tBTC token that the Acre protocol\\n /// can hold.\\n function updateDepositParameters(\\n uint256 _minimumDepositAmount,\\n uint256 _maximumTotalAssets\\n ) external onlyOwner {\\n // TODO: Introduce a parameters update process.\\n minimumDepositAmount = _minimumDepositAmount;\\n maximumTotalAssets = _maximumTotalAssets;\\n\\n emit DepositParametersUpdated(\\n _minimumDepositAmount,\\n _maximumTotalAssets\\n );\\n }\\n\\n // TODO: Implement a governed upgrade process that initiates an update and\\n // then finalizes it after a delay.\\n /// @notice Updates the dispatcher contract and gives it an unlimited\\n /// allowance to transfer staked tBTC.\\n /// @param newDispatcher Address of the new dispatcher contract.\\n function updateDispatcher(Dispatcher newDispatcher) external onlyOwner {\\n if (address(newDispatcher) == address(0)) {\\n revert ZeroAddress();\\n }\\n\\n address oldDispatcher = address(dispatcher);\\n\\n emit DispatcherUpdated(oldDispatcher, address(newDispatcher));\\n dispatcher = newDispatcher;\\n\\n // TODO: Once withdrawal/rebalancing is implemented, we need to revoke the\\n // approval of the vaults share tokens from the old dispatcher and approve\\n // a new dispatcher to manage the share tokens.\\n\\n if (oldDispatcher != address(0)) {\\n // Setting allowance to zero for the old dispatcher\\n IERC20(asset()).forceApprove(oldDispatcher, 0);\\n }\\n\\n // Setting allowance to max for the new dispatcher\\n IERC20(asset()).forceApprove(address(dispatcher), type(uint256).max);\\n }\\n\\n // TODO: Implement a governed upgrade process that initiates an update and\\n // then finalizes it after a delay.\\n /// @notice Update the entry fee basis points.\\n /// @param newEntryFeeBasisPoints New value of the fee basis points.\\n function updateEntryFeeBasisPoints(\\n uint256 newEntryFeeBasisPoints\\n ) external onlyOwner {\\n entryFeeBasisPoints = newEntryFeeBasisPoints;\\n\\n emit EntryFeeBasisPointsUpdated(newEntryFeeBasisPoints);\\n }\\n\\n /// @notice Mints shares to receiver by depositing exactly amount of\\n /// tBTC tokens.\\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\\n /// which determines the minimum amount for a single deposit operation.\\n /// The amount of the assets has to be pre-approved in the tBTC\\n /// contract.\\n /// @param assets Approved amount of tBTC tokens to deposit. This includes\\n /// treasury fees for staking tBTC.\\n /// @param receiver The address to which the shares will be minted.\\n /// @return Minted shares adjusted for the fees taken by the treasury.\\n function deposit(\\n uint256 assets,\\n address receiver\\n ) public override returns (uint256) {\\n if (assets < minimumDepositAmount) {\\n revert LessThanMinDeposit(assets, minimumDepositAmount);\\n }\\n\\n return super.deposit(assets, receiver);\\n }\\n\\n /// @notice Mints shares to receiver by depositing tBTC tokens.\\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\\n /// which determines the minimum amount for a single deposit operation.\\n /// The amount of the assets has to be pre-approved in the tBTC\\n /// contract.\\n /// The msg.sender is required to grant approval for the transfer of a\\n /// certain amount of tBTC, and in addition, approval for the associated\\n /// fee. Specifically, the total amount to be approved (amountToApprove)\\n /// should be equal to the sum of the deposited amount and the fee.\\n /// To determine the total assets amount necessary for approval\\n /// corresponding to a given share amount, use the `previewMint` function.\\n /// @param shares Amount of shares to mint.\\n /// @param receiver The address to which the shares will be minted.\\n function mint(\\n uint256 shares,\\n address receiver\\n ) public override returns (uint256 assets) {\\n if ((assets = super.mint(shares, receiver)) < minimumDepositAmount) {\\n revert LessThanMinDeposit(assets, minimumDepositAmount);\\n }\\n }\\n\\n /// @notice Stakes a given amount of tBTC token and mints shares to a\\n /// receiver.\\n /// @dev This function calls `deposit` function from `ERC4626` contract. The\\n /// amount of the assets has to be pre-approved in the tBTC contract.\\n /// @param assets Approved amount for the transfer and stake.\\n /// @param receiver The address to which the shares will be minted.\\n /// @param referral Data used for referral program.\\n /// @return shares Minted shares.\\n function stake(\\n uint256 assets,\\n address receiver,\\n uint16 referral\\n ) public returns (uint256) {\\n // TODO: revisit the type of referral.\\n uint256 shares = deposit(assets, receiver);\\n\\n if (referral > 0) {\\n emit StakeReferral(referral, assets);\\n }\\n\\n return shares;\\n }\\n\\n /// @notice Returns the maximum amount of the tBTC token that can be\\n /// deposited into the vault for the receiver through a deposit\\n /// call. It takes into account the deposit parameter, maximum total\\n /// assets, which determines the total amount of tBTC token held by\\n /// Acre. This function always returns available limit for deposits,\\n /// but the fee is not taken into account. As a result of this, there\\n /// always will be some dust left. If the dust is lower than the\\n /// minimum deposit amount, this function will return 0.\\n /// @return The maximum amount of tBTC token that can be deposited into\\n /// Acre protocol for the receiver.\\n function maxDeposit(address) public view override returns (uint256) {\\n if (maximumTotalAssets == type(uint256).max) {\\n return type(uint256).max;\\n }\\n\\n uint256 currentTotalAssets = totalAssets();\\n if (currentTotalAssets >= maximumTotalAssets) return 0;\\n\\n // Max amount left for next deposits. If it is lower than the minimum\\n // deposit amount, return 0.\\n uint256 unusedLimit = maximumTotalAssets - currentTotalAssets;\\n\\n return minimumDepositAmount > unusedLimit ? 0 : unusedLimit;\\n }\\n\\n /// @notice Returns the maximum amount of the vault shares that can be\\n /// minted for the receiver, through a mint call.\\n /// @dev Since the stBTC contract limits the maximum total tBTC tokens this\\n /// function converts the maximum deposit amount to shares.\\n /// @return The maximum amount of the vault shares.\\n function maxMint(address receiver) public view override returns (uint256) {\\n uint256 _maxDeposit = maxDeposit(receiver);\\n\\n // slither-disable-next-line incorrect-equality\\n return\\n _maxDeposit == type(uint256).max\\n ? type(uint256).max\\n : convertToShares(_maxDeposit);\\n }\\n\\n /// @return Returns deposit parameters.\\n function depositParameters() public view returns (uint256, uint256) {\\n return (minimumDepositAmount, maximumTotalAssets);\\n }\\n\\n /// @notice Redeems shares for tBTC tokens.\\n function _entryFeeBasisPoints() internal view override returns (uint256) {\\n return entryFeeBasisPoints;\\n }\\n\\n /// @notice Returns the address of the treasury wallet, where fees should be\\n /// transferred to.\\n function _feeRecipient() internal view override returns (address) {\\n return treasury;\\n }\\n}\\n\",\"keccak256\":\"0x5e622d3cef791a39b7089c64cacd5c62f14c13af316e2e8a3141244f7f69324e\",\"license\":\"GPL-3.0-only\"}},\"version\":1}", - "bytecode": "0x60c06040523480156200001157600080fd5b5060405162002459380380620024598339810160408190526200003491620002da565b33826040518060400160405280601381526020017f41637265205374616b656420426974636f696e0000000000000000000000000081525060405180604001604052806005815260200164737442544360d81b81525081600390816200009b9190620003be565b506004620000aa8282620003be565b505050600080620000c1836200018a60201b60201c565b9150915081620000d3576012620000d5565b805b60ff1660a05250506001600160a01b0390811660805281166200011257604051631e4fbdf760e01b81526000600482015260240160405180910390fd5b6200011d816200026f565b506001600160a01b038116620001465760405163d92e233d60e01b815260040160405180910390fd5b600780546001600160a01b0319166001600160a01b03929092169190911790555066038d7ea4c6800060095568015af1d78b58c40000600a556005600855620004d5565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290516000918291829182916001600160a01b03871691620001d3916200048a565b600060405180830381855afa9150503d806000811462000210576040519150601f19603f3d011682016040523d82523d6000602084013e62000215565b606091505b50915091508180156200022a57506020815110155b156200026257600081806020019051810190620002489190620004bb565b905060ff811162000260576001969095509350505050565b505b5060009485945092505050565b600580546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6001600160a01b0381168114620002d757600080fd5b50565b60008060408385031215620002ee57600080fd5b8251620002fb81620002c1565b60208401519092506200030e81620002c1565b809150509250929050565b634e487b7160e01b600052604160045260246000fd5b600181811c908216806200034457607f821691505b6020821081036200036557634e487b7160e01b600052602260045260246000fd5b50919050565b601f821115620003b957600081815260208120601f850160051c81016020861015620003945750805b601f850160051c820191505b81811015620003b557828155600101620003a0565b5050505b505050565b81516001600160401b03811115620003da57620003da62000319565b620003f281620003eb84546200032f565b846200036b565b602080601f8311600181146200042a5760008415620004115750858301515b600019600386901b1c1916600185901b178555620003b5565b600085815260208120601f198616915b828110156200045b578886015182559484019460019091019084016200043a565b50858210156200047a5787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b6000825160005b81811015620004ad576020818601810151858301520162000491565b506000920191825250919050565b600060208284031215620004ce57600080fd5b5051919050565b60805160a051611f3462000525600039600061077201526000818161036b01528181610602015281816108a9015281816108ee01528181611209015281816116bc015261186e0152611f346000f3fe608060405234801561001057600080fd5b50600436106102ad5760003560e01c80638da5cb5b1161017b578063c6e6f592116100d8578063dc8c4ffe1161008c578063e9c092e311610071578063e9c092e314610598578063ef8b30f7146105ab578063f2fde38b146105be57600080fd5b8063dc8c4ffe1461054c578063dd62ed3e1461055f57600080fd5b8063ce96cb77116100bd578063ce96cb7714610513578063d57636c914610526578063d905777e1461053957600080fd5b8063c6e6f592146104ed578063cb7e90571461050057600080fd5b8063b460af941161012f578063ba0af7a911610114578063ba0af7a9146104b6578063c42b64d0146104bf578063c63d75b6146104da57600080fd5b8063b460af9414610490578063ba087652146104a357600080fd5b806395d89b411161016057806395d89b4114610462578063a9059cbb1461046a578063b3d7f6b91461047d57600080fd5b80638da5cb5b1461043e57806394bf804d1461044f57600080fd5b806338d52e0f1161022957806361d027b3116101dd57806370a08231116101c257806370a08231146103fa578063715018a6146104235780637f51bb1f1461042b57600080fd5b806361d027b3146103d45780636e553f65146103e757600080fd5b806342af11981161020e57806342af1198146103b65780634cdad506146102e2578063543bda75146103cb57600080fd5b806338d52e0f14610369578063402d267d146103a357600080fd5b8063095ea7b31161028057806318160ddd1161026557806318160ddd1461033457806323b872dd1461033c578063313ce5671461034f57600080fd5b8063095ea7b3146102fe5780630a28a4771461032157600080fd5b806301e1d114146102b257806306fdde03146102cd57806307a2d13a146102e2578063080c279a146102f5575b600080fd5b6102ba6105d1565b6040519081526020015b60405180910390f35b6102d561067a565b6040516102c49190611ade565b6102ba6102f0366004611b11565b61070c565b6102ba60095481565b61031161030c366004611b3f565b61071f565b60405190151581526020016102c4565b6102ba61032f366004611b11565b610737565b6002546102ba565b61031161034a366004611b6b565b610744565b61035761076a565b60405160ff90911681526020016102c4565b7f00000000000000000000000000000000000000000000000000000000000000005b6040516001600160a01b0390911681526020016102c4565b6102ba6103b1366004611bac565b610796565b6103c96103c4366004611bac565b6107f6565b005b6102ba600a5481565b60075461038b906001600160a01b031681565b6102ba6103f5366004611bc9565b610916565b6102ba610408366004611bac565b6001600160a01b031660009081526020819052604090205490565b6103c961095c565b6103c9610439366004611bac565b610970565b6005546001600160a01b031661038b565b6102ba61045d366004611bc9565b610a43565b6102d5610a82565b610311610478366004611b3f565b610a91565b6102ba61048b366004611b11565b610a9f565b6102ba61049e366004611bf9565b610ac9565b6102ba6104b1366004611bf9565b610b4d565b6102ba60085481565b600954600a54604080519283526020830191909152016102c4565b6102ba6104e8366004611bac565b610bc8565b6102ba6104fb366004611b11565b610bf7565b60065461038b906001600160a01b031681565b6102ba610521366004611bac565b610c04565b6103c9610534366004611b11565b610c28565b6102ba610547366004611bac565b610c65565b6102ba61055a366004611c3b565b610c83565b6102ba61056d366004611c79565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6103c96105a6366004611ca7565b610ce2565b6102ba6105b9366004611b11565b610d31565b6103c96105cc366004611bac565b610d55565b6040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015610651573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106759190611cc9565b905090565b60606003805461068990611ce2565b80601f01602080910402602001604051908101604052809291908181526020018280546106b590611ce2565b80156107025780601f106106d757610100808354040283529160200191610702565b820191906000526020600020905b8154815290600101906020018083116106e557829003601f168201915b5050505050905090565b6000610719826000610dac565b92915050565b60003361072d818585610de6565b5060019392505050565b6000610719826001610df8565b600033610752858285610e28565b61075d858585610ebf565b60019150505b9392505050565b6000610675817f0000000000000000000000000000000000000000000000000000000000000000611d32565b6000600019600a54036107ac5750600019919050565b60006107b66105d1565b9050600a5481106107ca5750600092915050565b600081600a546107da9190611d4b565b905080600954116107eb57806107ee565b60005b949350505050565b6107fe610f1e565b6001600160a01b0381166108255760405163d92e233d60e01b815260040160405180910390fd5b600654604080516001600160a01b0392831680825292841660208201527ff6e490308a0c67484cf1082cb89a68053c7a7bbf474247e8b634957e2ce2f296910160405180910390a16006805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03848116919091179091558116156108d9576108d98160007f00000000000000000000000000000000000000000000000000000000000000005b6001600160a01b03169190610f64565b600654610912906001600160a01b03166000197f00000000000000000000000000000000000000000000000000000000000000006108c9565b5050565b6000600954831015610952576009546040516314d6e77b60e31b8152610949918591600401918252602082015260400190565b60405180910390fd5b6107638383611065565b610964610f1e565b61096e60006110df565b565b610978610f1e565b6001600160a01b03811661099f5760405163d92e233d60e01b815260040160405180910390fd5b306001600160a01b038216036109e1576040517f593230f700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6007805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0383169081179091556040519081527f7dae230f18360d76a040c81f050aa14eb9d6dc7901b20fc5d855e2a20fe814d1906020015b60405180910390a150565b6000600954610a52848461113e565b9150811015610719576009546040516314d6e77b60e31b8152610949918391600401918252602082015260400190565b60606004805461068990611ce2565b60003361072d818585610ebf565b600080610aab836111b8565b9050610abf81610aba60085490565b6111c5565b6107639082611d5e565b600080610ad583610c04565b905080851115610b2a576040517ffe9cceec0000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810186905260448101829052606401610949565b6000610b3586610737565b9050610b4433868689856111d6565b95945050505050565b600080610b5983610c65565b905080851115610bae576040517fb94abeec0000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810186905260448101829052606401610949565b6000610bb98661070c565b9050610b44338686848a6111d6565b600080610bd483610796565b90506000198114610bed57610be881610bf7565b610763565b6000199392505050565b6000610719826000610df8565b6001600160a01b038116600090815260208190526040812054610719906000610dac565b610c30610f1e565b60088190556040518181527f5af127f521fefc539e7e224fd330591102c4288877cf9b83c5d8a100cbb88ceb90602001610a38565b6001600160a01b038116600090815260208190526040812054610719565b600080610c908585610916565b905061ffff8316156107ee578261ffff167f246e5dcdb71dfbdc1088d365e35a9f8e3aefefebf0b9bee103bf4f3a2edec12b86604051610cd291815260200190565b60405180910390a2949350505050565b610cea610f1e565b6009829055600a81905560408051838152602081018390527f5543b97d9277fef57d70edac6c4c10f4426957b886dfe97286c01d2218a53280910160405180910390a15050565b600080610d4683610d4160085490565b611296565b90506107636104fb8285611d4b565b610d5d610f1e565b6001600160a01b038116610da0576040517f1e4fbdf700000000000000000000000000000000000000000000000000000000815260006004820152602401610949565b610da9816110df565b50565b6000610763610db96105d1565b610dc4906001611d5e565b610dd06000600a611e55565b600254610ddd9190611d5e565b859190856112ae565b610df383838360016112fd565b505050565b6000610763610e0882600a611e55565b600254610e159190611d5e565b610e1d6105d1565b610ddd906001611d5e565b6001600160a01b038381166000908152600160209081526040808320938616835292905220546000198114610eb95781811015610eaa576040517ffb8f41b20000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810182905260448101839052606401610949565b610eb9848484840360006112fd565b50505050565b6001600160a01b038316610ee957604051634b637e8f60e11b815260006004820152602401610949565b6001600160a01b038216610f135760405163ec442f0560e01b815260006004820152602401610949565b610df3838383611404565b6005546001600160a01b0316331461096e576040517f118cdaa7000000000000000000000000000000000000000000000000000000008152336004820152602401610949565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f095ea7b300000000000000000000000000000000000000000000000000000000179052610fe38482611547565b610eb9576040516001600160a01b0384811660248301526000604483015261105b91869182169063095ea7b3906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506115ea565b610eb984826115ea565b60008061107183610796565b9050808411156110c6576040517f79012fb20000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810185905260448101829052606401610949565b60006110d185610d31565b90506107ee33858784611666565b600580546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b60008061114a83610bc8565b90508084111561119f576040517f284ff6670000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810185905260448101829052606401610949565b60006111aa85610a9f565b90506107ee33858388611666565b6000610719826001610dac565b6000610763838361271060016112ae565b826001600160a01b0316856001600160a01b0316146111fa576111fa838683610e28565b61120483826116ea565b61122f7f00000000000000000000000000000000000000000000000000000000000000008584611720565b826001600160a01b0316846001600160a01b0316866001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8585604051611287929190918252602082015260400190565b60405180910390a45050505050565b6000610763826112a861271082611d5e565b85919060015b6000806112bc868686611751565b90506112c78361182e565b80156112e35750600084806112de576112de611e64565b868809115b15610b44576112f3600182611d5e565b9695505050505050565b6001600160a01b038416611340576040517fe602df0500000000000000000000000000000000000000000000000000000000815260006004820152602401610949565b6001600160a01b038316611383576040517f94280d6200000000000000000000000000000000000000000000000000000000815260006004820152602401610949565b6001600160a01b0380851660009081526001602090815260408083209387168352929052208290558015610eb957826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516113f691815260200190565b60405180910390a350505050565b6001600160a01b03831661142f5780600260008282546114249190611d5e565b909155506114ba9050565b6001600160a01b0383166000908152602081905260409020548181101561149b576040517fe450d38c0000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024810182905260448101839052606401610949565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b0382166114d6576002805482900390556114f5565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8360405161153a91815260200190565b60405180910390a3505050565b6000806000846001600160a01b0316846040516115649190611e7a565b6000604051808303816000865af19150503d80600081146115a1576040519150601f19603f3d011682016040523d82523d6000602084013e6115a6565b606091505b50915091508180156115d05750805115806115d05750808060200190518101906115d09190611e96565b8015610b445750505050506001600160a01b03163b151590565b60006115ff6001600160a01b0384168361185b565b905080516000141580156116245750808060200190518101906116229190611e96565b155b15610df3576040517f5274afe70000000000000000000000000000000000000000000000000000000081526001600160a01b0384166004820152602401610949565b600061167583610d4160085490565b9050600061168b6007546001600160a01b031690565b905061169986868686611869565b6000821180156116b257506001600160a01b0381163014155b156116e2576116e27f00000000000000000000000000000000000000000000000000000000000000008284611720565b505050505050565b6001600160a01b03821661171457604051634b637e8f60e11b815260006004820152602401610949565b61091282600083611404565b6040516001600160a01b03838116602483015260448201839052610df391859182169063a9059cbb90606401611014565b60008383028160001985870982811083820303915050806000036117885783828161177e5761177e611e64565b0492505050610763565b8084116117c1576040517f227bc15300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b6000600282600381111561184457611844611eb8565b61184e9190611ece565b60ff166001149050919050565b6060610763838360006118ed565b6118957f0000000000000000000000000000000000000000000000000000000000000000853085611999565b61189f83826119d2565b826001600160a01b0316846001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d784846040516113f6929190918252602082015260400190565b60608147101561192b576040517fcd786059000000000000000000000000000000000000000000000000000000008152306004820152602401610949565b600080856001600160a01b031684866040516119479190611e7a565b60006040518083038185875af1925050503d8060008114611984576040519150601f19603f3d011682016040523d82523d6000602084013e611989565b606091505b50915091506112f3868383611a08565b6040516001600160a01b038481166024830152838116604483015260648201839052610eb99186918216906323b872dd90608401611014565b6001600160a01b0382166119fc5760405163ec442f0560e01b815260006004820152602401610949565b61091260008383611404565b606082611a1857610be882611a78565b8151158015611a2f57506001600160a01b0384163b155b15611a71576040517f9996b3150000000000000000000000000000000000000000000000000000000081526001600160a01b0385166004820152602401610949565b5080610763565b805115611a885780518082602001fd5b6040517f1425ea4200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60005b83811015611ad5578181015183820152602001611abd565b50506000910152565b6020815260008251806020840152611afd816040850160208701611aba565b601f01601f19169190910160400192915050565b600060208284031215611b2357600080fd5b5035919050565b6001600160a01b0381168114610da957600080fd5b60008060408385031215611b5257600080fd5b8235611b5d81611b2a565b946020939093013593505050565b600080600060608486031215611b8057600080fd5b8335611b8b81611b2a565b92506020840135611b9b81611b2a565b929592945050506040919091013590565b600060208284031215611bbe57600080fd5b813561076381611b2a565b60008060408385031215611bdc57600080fd5b823591506020830135611bee81611b2a565b809150509250929050565b600080600060608486031215611c0e57600080fd5b833592506020840135611c2081611b2a565b91506040840135611c3081611b2a565b809150509250925092565b600080600060608486031215611c5057600080fd5b833592506020840135611c6281611b2a565b9150604084013561ffff81168114611c3057600080fd5b60008060408385031215611c8c57600080fd5b8235611c9781611b2a565b91506020830135611bee81611b2a565b60008060408385031215611cba57600080fd5b50508035926020909101359150565b600060208284031215611cdb57600080fd5b5051919050565b600181811c90821680611cf657607f821691505b602082108103611d1657634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b60ff818116838216019081111561071957610719611d1c565b8181038181111561071957610719611d1c565b8082018082111561071957610719611d1c565b600181815b80851115611dac578160001904821115611d9257611d92611d1c565b80851615611d9f57918102915b93841c9390800290611d76565b509250929050565b600082611dc357506001610719565b81611dd057506000610719565b8160018114611de65760028114611df057611e0c565b6001915050610719565b60ff841115611e0157611e01611d1c565b50506001821b610719565b5060208310610133831016604e8410600b8410161715611e2f575081810a610719565b611e398383611d71565b8060001904821115611e4d57611e4d611d1c565b029392505050565b600061076360ff841683611db4565b634e487b7160e01b600052601260045260246000fd5b60008251611e8c818460208701611aba565b9190910192915050565b600060208284031215611ea857600080fd5b8151801515811461076357600080fd5b634e487b7160e01b600052602160045260246000fd5b600060ff831680611eef57634e487b7160e01b600052601260045260246000fd5b8060ff8416069150509291505056fea264697066735822122078be0d61f06be7b31d82934e38e0e01f533e761933d73e729a05ac0e4d4cba7164736f6c63430008150033", - "deployedBytecode": "0x608060405234801561001057600080fd5b50600436106102ad5760003560e01c80638da5cb5b1161017b578063c6e6f592116100d8578063dc8c4ffe1161008c578063e9c092e311610071578063e9c092e314610598578063ef8b30f7146105ab578063f2fde38b146105be57600080fd5b8063dc8c4ffe1461054c578063dd62ed3e1461055f57600080fd5b8063ce96cb77116100bd578063ce96cb7714610513578063d57636c914610526578063d905777e1461053957600080fd5b8063c6e6f592146104ed578063cb7e90571461050057600080fd5b8063b460af941161012f578063ba0af7a911610114578063ba0af7a9146104b6578063c42b64d0146104bf578063c63d75b6146104da57600080fd5b8063b460af9414610490578063ba087652146104a357600080fd5b806395d89b411161016057806395d89b4114610462578063a9059cbb1461046a578063b3d7f6b91461047d57600080fd5b80638da5cb5b1461043e57806394bf804d1461044f57600080fd5b806338d52e0f1161022957806361d027b3116101dd57806370a08231116101c257806370a08231146103fa578063715018a6146104235780637f51bb1f1461042b57600080fd5b806361d027b3146103d45780636e553f65146103e757600080fd5b806342af11981161020e57806342af1198146103b65780634cdad506146102e2578063543bda75146103cb57600080fd5b806338d52e0f14610369578063402d267d146103a357600080fd5b8063095ea7b31161028057806318160ddd1161026557806318160ddd1461033457806323b872dd1461033c578063313ce5671461034f57600080fd5b8063095ea7b3146102fe5780630a28a4771461032157600080fd5b806301e1d114146102b257806306fdde03146102cd57806307a2d13a146102e2578063080c279a146102f5575b600080fd5b6102ba6105d1565b6040519081526020015b60405180910390f35b6102d561067a565b6040516102c49190611ade565b6102ba6102f0366004611b11565b61070c565b6102ba60095481565b61031161030c366004611b3f565b61071f565b60405190151581526020016102c4565b6102ba61032f366004611b11565b610737565b6002546102ba565b61031161034a366004611b6b565b610744565b61035761076a565b60405160ff90911681526020016102c4565b7f00000000000000000000000000000000000000000000000000000000000000005b6040516001600160a01b0390911681526020016102c4565b6102ba6103b1366004611bac565b610796565b6103c96103c4366004611bac565b6107f6565b005b6102ba600a5481565b60075461038b906001600160a01b031681565b6102ba6103f5366004611bc9565b610916565b6102ba610408366004611bac565b6001600160a01b031660009081526020819052604090205490565b6103c961095c565b6103c9610439366004611bac565b610970565b6005546001600160a01b031661038b565b6102ba61045d366004611bc9565b610a43565b6102d5610a82565b610311610478366004611b3f565b610a91565b6102ba61048b366004611b11565b610a9f565b6102ba61049e366004611bf9565b610ac9565b6102ba6104b1366004611bf9565b610b4d565b6102ba60085481565b600954600a54604080519283526020830191909152016102c4565b6102ba6104e8366004611bac565b610bc8565b6102ba6104fb366004611b11565b610bf7565b60065461038b906001600160a01b031681565b6102ba610521366004611bac565b610c04565b6103c9610534366004611b11565b610c28565b6102ba610547366004611bac565b610c65565b6102ba61055a366004611c3b565b610c83565b6102ba61056d366004611c79565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6103c96105a6366004611ca7565b610ce2565b6102ba6105b9366004611b11565b610d31565b6103c96105cc366004611bac565b610d55565b6040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015610651573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106759190611cc9565b905090565b60606003805461068990611ce2565b80601f01602080910402602001604051908101604052809291908181526020018280546106b590611ce2565b80156107025780601f106106d757610100808354040283529160200191610702565b820191906000526020600020905b8154815290600101906020018083116106e557829003601f168201915b5050505050905090565b6000610719826000610dac565b92915050565b60003361072d818585610de6565b5060019392505050565b6000610719826001610df8565b600033610752858285610e28565b61075d858585610ebf565b60019150505b9392505050565b6000610675817f0000000000000000000000000000000000000000000000000000000000000000611d32565b6000600019600a54036107ac5750600019919050565b60006107b66105d1565b9050600a5481106107ca5750600092915050565b600081600a546107da9190611d4b565b905080600954116107eb57806107ee565b60005b949350505050565b6107fe610f1e565b6001600160a01b0381166108255760405163d92e233d60e01b815260040160405180910390fd5b600654604080516001600160a01b0392831680825292841660208201527ff6e490308a0c67484cf1082cb89a68053c7a7bbf474247e8b634957e2ce2f296910160405180910390a16006805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03848116919091179091558116156108d9576108d98160007f00000000000000000000000000000000000000000000000000000000000000005b6001600160a01b03169190610f64565b600654610912906001600160a01b03166000197f00000000000000000000000000000000000000000000000000000000000000006108c9565b5050565b6000600954831015610952576009546040516314d6e77b60e31b8152610949918591600401918252602082015260400190565b60405180910390fd5b6107638383611065565b610964610f1e565b61096e60006110df565b565b610978610f1e565b6001600160a01b03811661099f5760405163d92e233d60e01b815260040160405180910390fd5b306001600160a01b038216036109e1576040517f593230f700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6007805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0383169081179091556040519081527f7dae230f18360d76a040c81f050aa14eb9d6dc7901b20fc5d855e2a20fe814d1906020015b60405180910390a150565b6000600954610a52848461113e565b9150811015610719576009546040516314d6e77b60e31b8152610949918391600401918252602082015260400190565b60606004805461068990611ce2565b60003361072d818585610ebf565b600080610aab836111b8565b9050610abf81610aba60085490565b6111c5565b6107639082611d5e565b600080610ad583610c04565b905080851115610b2a576040517ffe9cceec0000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810186905260448101829052606401610949565b6000610b3586610737565b9050610b4433868689856111d6565b95945050505050565b600080610b5983610c65565b905080851115610bae576040517fb94abeec0000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810186905260448101829052606401610949565b6000610bb98661070c565b9050610b44338686848a6111d6565b600080610bd483610796565b90506000198114610bed57610be881610bf7565b610763565b6000199392505050565b6000610719826000610df8565b6001600160a01b038116600090815260208190526040812054610719906000610dac565b610c30610f1e565b60088190556040518181527f5af127f521fefc539e7e224fd330591102c4288877cf9b83c5d8a100cbb88ceb90602001610a38565b6001600160a01b038116600090815260208190526040812054610719565b600080610c908585610916565b905061ffff8316156107ee578261ffff167f246e5dcdb71dfbdc1088d365e35a9f8e3aefefebf0b9bee103bf4f3a2edec12b86604051610cd291815260200190565b60405180910390a2949350505050565b610cea610f1e565b6009829055600a81905560408051838152602081018390527f5543b97d9277fef57d70edac6c4c10f4426957b886dfe97286c01d2218a53280910160405180910390a15050565b600080610d4683610d4160085490565b611296565b90506107636104fb8285611d4b565b610d5d610f1e565b6001600160a01b038116610da0576040517f1e4fbdf700000000000000000000000000000000000000000000000000000000815260006004820152602401610949565b610da9816110df565b50565b6000610763610db96105d1565b610dc4906001611d5e565b610dd06000600a611e55565b600254610ddd9190611d5e565b859190856112ae565b610df383838360016112fd565b505050565b6000610763610e0882600a611e55565b600254610e159190611d5e565b610e1d6105d1565b610ddd906001611d5e565b6001600160a01b038381166000908152600160209081526040808320938616835292905220546000198114610eb95781811015610eaa576040517ffb8f41b20000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810182905260448101839052606401610949565b610eb9848484840360006112fd565b50505050565b6001600160a01b038316610ee957604051634b637e8f60e11b815260006004820152602401610949565b6001600160a01b038216610f135760405163ec442f0560e01b815260006004820152602401610949565b610df3838383611404565b6005546001600160a01b0316331461096e576040517f118cdaa7000000000000000000000000000000000000000000000000000000008152336004820152602401610949565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f095ea7b300000000000000000000000000000000000000000000000000000000179052610fe38482611547565b610eb9576040516001600160a01b0384811660248301526000604483015261105b91869182169063095ea7b3906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506115ea565b610eb984826115ea565b60008061107183610796565b9050808411156110c6576040517f79012fb20000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810185905260448101829052606401610949565b60006110d185610d31565b90506107ee33858784611666565b600580546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b60008061114a83610bc8565b90508084111561119f576040517f284ff6670000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024810185905260448101829052606401610949565b60006111aa85610a9f565b90506107ee33858388611666565b6000610719826001610dac565b6000610763838361271060016112ae565b826001600160a01b0316856001600160a01b0316146111fa576111fa838683610e28565b61120483826116ea565b61122f7f00000000000000000000000000000000000000000000000000000000000000008584611720565b826001600160a01b0316846001600160a01b0316866001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8585604051611287929190918252602082015260400190565b60405180910390a45050505050565b6000610763826112a861271082611d5e565b85919060015b6000806112bc868686611751565b90506112c78361182e565b80156112e35750600084806112de576112de611e64565b868809115b15610b44576112f3600182611d5e565b9695505050505050565b6001600160a01b038416611340576040517fe602df0500000000000000000000000000000000000000000000000000000000815260006004820152602401610949565b6001600160a01b038316611383576040517f94280d6200000000000000000000000000000000000000000000000000000000815260006004820152602401610949565b6001600160a01b0380851660009081526001602090815260408083209387168352929052208290558015610eb957826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516113f691815260200190565b60405180910390a350505050565b6001600160a01b03831661142f5780600260008282546114249190611d5e565b909155506114ba9050565b6001600160a01b0383166000908152602081905260409020548181101561149b576040517fe450d38c0000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024810182905260448101839052606401610949565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b0382166114d6576002805482900390556114f5565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8360405161153a91815260200190565b60405180910390a3505050565b6000806000846001600160a01b0316846040516115649190611e7a565b6000604051808303816000865af19150503d80600081146115a1576040519150601f19603f3d011682016040523d82523d6000602084013e6115a6565b606091505b50915091508180156115d05750805115806115d05750808060200190518101906115d09190611e96565b8015610b445750505050506001600160a01b03163b151590565b60006115ff6001600160a01b0384168361185b565b905080516000141580156116245750808060200190518101906116229190611e96565b155b15610df3576040517f5274afe70000000000000000000000000000000000000000000000000000000081526001600160a01b0384166004820152602401610949565b600061167583610d4160085490565b9050600061168b6007546001600160a01b031690565b905061169986868686611869565b6000821180156116b257506001600160a01b0381163014155b156116e2576116e27f00000000000000000000000000000000000000000000000000000000000000008284611720565b505050505050565b6001600160a01b03821661171457604051634b637e8f60e11b815260006004820152602401610949565b61091282600083611404565b6040516001600160a01b03838116602483015260448201839052610df391859182169063a9059cbb90606401611014565b60008383028160001985870982811083820303915050806000036117885783828161177e5761177e611e64565b0492505050610763565b8084116117c1576040517f227bc15300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b6000600282600381111561184457611844611eb8565b61184e9190611ece565b60ff166001149050919050565b6060610763838360006118ed565b6118957f0000000000000000000000000000000000000000000000000000000000000000853085611999565b61189f83826119d2565b826001600160a01b0316846001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d784846040516113f6929190918252602082015260400190565b60608147101561192b576040517fcd786059000000000000000000000000000000000000000000000000000000008152306004820152602401610949565b600080856001600160a01b031684866040516119479190611e7a565b60006040518083038185875af1925050503d8060008114611984576040519150601f19603f3d011682016040523d82523d6000602084013e611989565b606091505b50915091506112f3868383611a08565b6040516001600160a01b038481166024830152838116604483015260648201839052610eb99186918216906323b872dd90608401611014565b6001600160a01b0382166119fc5760405163ec442f0560e01b815260006004820152602401610949565b61091260008383611404565b606082611a1857610be882611a78565b8151158015611a2f57506001600160a01b0384163b155b15611a71576040517f9996b3150000000000000000000000000000000000000000000000000000000081526001600160a01b0385166004820152602401610949565b5080610763565b805115611a885780518082602001fd5b6040517f1425ea4200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60005b83811015611ad5578181015183820152602001611abd565b50506000910152565b6020815260008251806020840152611afd816040850160208701611aba565b601f01601f19169190910160400192915050565b600060208284031215611b2357600080fd5b5035919050565b6001600160a01b0381168114610da957600080fd5b60008060408385031215611b5257600080fd5b8235611b5d81611b2a565b946020939093013593505050565b600080600060608486031215611b8057600080fd5b8335611b8b81611b2a565b92506020840135611b9b81611b2a565b929592945050506040919091013590565b600060208284031215611bbe57600080fd5b813561076381611b2a565b60008060408385031215611bdc57600080fd5b823591506020830135611bee81611b2a565b809150509250929050565b600080600060608486031215611c0e57600080fd5b833592506020840135611c2081611b2a565b91506040840135611c3081611b2a565b809150509250925092565b600080600060608486031215611c5057600080fd5b833592506020840135611c6281611b2a565b9150604084013561ffff81168114611c3057600080fd5b60008060408385031215611c8c57600080fd5b8235611c9781611b2a565b91506020830135611bee81611b2a565b60008060408385031215611cba57600080fd5b50508035926020909101359150565b600060208284031215611cdb57600080fd5b5051919050565b600181811c90821680611cf657607f821691505b602082108103611d1657634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b60ff818116838216019081111561071957610719611d1c565b8181038181111561071957610719611d1c565b8082018082111561071957610719611d1c565b600181815b80851115611dac578160001904821115611d9257611d92611d1c565b80851615611d9f57918102915b93841c9390800290611d76565b509250929050565b600082611dc357506001610719565b81611dd057506000610719565b8160018114611de65760028114611df057611e0c565b6001915050610719565b60ff841115611e0157611e01611d1c565b50506001821b610719565b5060208310610133831016604e8410600b8410161715611e2f575081810a610719565b611e398383611d71565b8060001904821115611e4d57611e4d611d1c565b029392505050565b600061076360ff841683611db4565b634e487b7160e01b600052601260045260246000fd5b60008251611e8c818460208701611aba565b9190910192915050565b600060208284031215611ea857600080fd5b8151801515811461076357600080fd5b634e487b7160e01b600052602160045260246000fd5b600060ff831680611eef57634e487b7160e01b600052601260045260246000fd5b8060ff8416069150509291505056fea264697066735822122078be0d61f06be7b31d82934e38e0e01f533e761933d73e729a05ac0e4d4cba7164736f6c63430008150033", - "devdoc": { - "details": "ERC-4626 is a standard to optimize and unify the technical parameters of yield-bearing vaults. This contract facilitates the minting and burning of shares (stBTC), which are represented as standard ERC20 tokens, providing a seamless exchange with tBTC tokens.", - "errors": { - "AddressEmptyCode(address)": [ - { - "details": "There's no code at `target` (it is not a contract)." - } - ], - "AddressInsufficientBalance(address)": [ - { - "details": "The ETH balance of the account is not enough to perform the operation." - } - ], - "ERC20InsufficientAllowance(address,uint256,uint256)": [ - { - "details": "Indicates a failure with the `spender`’s `allowance`. Used in transfers.", - "params": { - "allowance": "Amount of tokens a `spender` is allowed to operate with.", - "needed": "Minimum amount required to perform a transfer.", - "spender": "Address that may be allowed to operate on tokens without being their owner." - } - } - ], - "ERC20InsufficientBalance(address,uint256,uint256)": [ - { - "details": "Indicates an error related to the current `balance` of a `sender`. Used in transfers.", - "params": { - "balance": "Current balance for the interacting account.", - "needed": "Minimum amount required to perform a transfer.", - "sender": "Address whose tokens are being transferred." - } - } - ], - "ERC20InvalidApprover(address)": [ - { - "details": "Indicates a failure with the `approver` of a token to be approved. Used in approvals.", - "params": { - "approver": "Address initiating an approval operation." - } - } - ], - "ERC20InvalidReceiver(address)": [ - { - "details": "Indicates a failure with the token `receiver`. Used in transfers.", - "params": { - "receiver": "Address to which tokens are being transferred." - } - } - ], - "ERC20InvalidSender(address)": [ - { - "details": "Indicates a failure with the token `sender`. Used in transfers.", - "params": { - "sender": "Address whose tokens are being transferred." - } - } - ], - "ERC20InvalidSpender(address)": [ - { - "details": "Indicates a failure with the `spender` to be approved. Used in approvals.", - "params": { - "spender": "Address that may be allowed to operate on tokens without being their owner." - } - } - ], - "ERC4626ExceededMaxDeposit(address,uint256,uint256)": [ - { - "details": "Attempted to deposit more assets than the max amount for `receiver`." - } - ], - "ERC4626ExceededMaxMint(address,uint256,uint256)": [ - { - "details": "Attempted to mint more shares than the max amount for `receiver`." - } - ], - "ERC4626ExceededMaxRedeem(address,uint256,uint256)": [ - { - "details": "Attempted to redeem more shares than the max amount for `receiver`." - } - ], - "ERC4626ExceededMaxWithdraw(address,uint256,uint256)": [ - { - "details": "Attempted to withdraw more assets than the max amount for `receiver`." - } - ], - "FailedInnerCall()": [ - { - "details": "A call to an address target failed. The target may have reverted." - } - ], - "LessThanMinDeposit(uint256,uint256)": [ - { - "params": { - "amount": "Amount to check.", - "min": "Minimum amount to check 'amount' against." - } - } - ], - "MathOverflowedMulDiv()": [ - { - "details": "Muldiv operation overflow." - } - ], - "OwnableInvalidOwner(address)": [ - { - "details": "The owner is not a valid owner account. (eg. `address(0)`)" - } - ], - "OwnableUnauthorizedAccount(address)": [ - { - "details": "The caller account is not authorized to perform an operation." - } - ], - "SafeERC20FailedOperation(address)": [ - { - "details": "An operation with an ERC20 token failed." - } - ] - }, - "events": { - "Approval(address,address,uint256)": { - "details": "Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance." - }, - "DepositParametersUpdated(uint256,uint256)": { - "params": { - "maximumTotalAssets": "New value of the maximum total assets amount.", - "minimumDepositAmount": "New value of the minimum deposit amount." - } - }, - "DispatcherUpdated(address,address)": { - "params": { - "newDispatcher": "Address of the new dispatcher contract.", - "oldDispatcher": "Address of the old dispatcher contract." - } - }, - "EntryFeeBasisPointsUpdated(uint256)": { - "params": { - "entryFeeBasisPoints": "New value of the fee basis points." - } - }, - "StakeReferral(uint16,uint256)": { - "params": { - "assets": "Amount of tBTC tokens staked.", - "referral": "Used for referral program." - } - }, - "Transfer(address,address,uint256)": { - "details": "Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero." - }, - "TreasuryUpdated(address)": { - "params": { - "treasury": "New treasury wallet address." - } - } - }, - "kind": "dev", - "methods": { - "allowance(address,address)": { - "details": "See {IERC20-allowance}." - }, - "approve(address,uint256)": { - "details": "See {IERC20-approve}. NOTE: If `value` is the maximum `uint256`, the allowance is not updated on `transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address." - }, - "asset()": { - "details": "See {IERC4626-asset}. " - }, - "balanceOf(address)": { - "details": "See {IERC20-balanceOf}." - }, - "convertToAssets(uint256)": { - "details": "See {IERC4626-convertToAssets}. " - }, - "convertToShares(uint256)": { - "details": "See {IERC4626-convertToShares}. " - }, - "decimals()": { - "details": "Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This \"original\" value is cached during construction of the vault contract. If this read operation fails (e.g., the asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals. See {IERC20Metadata-decimals}." - }, - "deposit(uint256,address)": { - "details": "Takes into account a deposit parameter, minimum deposit amount, which determines the minimum amount for a single deposit operation. The amount of the assets has to be pre-approved in the tBTC contract.", - "params": { - "assets": "Approved amount of tBTC tokens to deposit. This includes treasury fees for staking tBTC.", - "receiver": "The address to which the shares will be minted." - }, - "returns": { - "_0": "Minted shares adjusted for the fees taken by the treasury." - } - }, - "depositParameters()": { - "returns": { - "_0": "Returns deposit parameters." - } - }, - "maxDeposit(address)": { - "returns": { - "_0": "The maximum amount of tBTC token that can be deposited into Acre protocol for the receiver." - } - }, - "maxMint(address)": { - "details": "Since the stBTC contract limits the maximum total tBTC tokens this function converts the maximum deposit amount to shares.", - "returns": { - "_0": "The maximum amount of the vault shares." - } - }, - "maxRedeem(address)": { - "details": "See {IERC4626-maxRedeem}. " - }, - "maxWithdraw(address)": { - "details": "See {IERC4626-maxWithdraw}. " - }, - "mint(uint256,address)": { - "details": "Takes into account a deposit parameter, minimum deposit amount, which determines the minimum amount for a single deposit operation. The amount of the assets has to be pre-approved in the tBTC contract. The msg.sender is required to grant approval for the transfer of a certain amount of tBTC, and in addition, approval for the associated fee. Specifically, the total amount to be approved (amountToApprove) should be equal to the sum of the deposited amount and the fee. To determine the total assets amount necessary for approval corresponding to a given share amount, use the `previewMint` function.", - "params": { - "receiver": "The address to which the shares will be minted.", - "shares": "Amount of shares to mint." - } - }, - "name()": { - "details": "Returns the name of the token." - }, - "owner()": { - "details": "Returns the address of the current owner." - }, - "previewDeposit(uint256)": { - "details": "Preview taking an entry fee on deposit. See {IERC4626-previewDeposit}." - }, - "previewMint(uint256)": { - "details": "Preview adding an entry fee on mint. See {IERC4626-previewMint}." - }, - "previewRedeem(uint256)": { - "details": "See {IERC4626-previewRedeem}. " - }, - "previewWithdraw(uint256)": { - "details": "See {IERC4626-previewWithdraw}. " - }, - "redeem(uint256,address,address)": { - "details": "See {IERC4626-redeem}. " - }, - "renounceOwnership()": { - "details": "Leaves the contract without owner. It will not be possible to call `onlyOwner` functions. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby disabling any functionality that is only available to the owner." - }, - "stake(uint256,address,uint16)": { - "details": "This function calls `deposit` function from `ERC4626` contract. The amount of the assets has to be pre-approved in the tBTC contract.", - "params": { - "assets": "Approved amount for the transfer and stake.", - "receiver": "The address to which the shares will be minted.", - "referral": "Data used for referral program." - }, - "returns": { - "_0": "shares Minted shares." - } - }, - "symbol()": { - "details": "Returns the symbol of the token, usually a shorter version of the name." - }, - "totalAssets()": { - "details": "See {IERC4626-totalAssets}. " - }, - "totalSupply()": { - "details": "See {IERC20-totalSupply}." - }, - "transfer(address,uint256)": { - "details": "See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `value`." - }, - "transferFrom(address,address,uint256)": { - "details": "See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowance is the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address. - `from` must have a balance of at least `value`. - the caller must have allowance for ``from``'s tokens of at least `value`." - }, - "transferOwnership(address)": { - "details": "Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner." - }, - "updateDepositParameters(uint256,uint256)": { - "details": "To disable the limit for deposits, set the maximum total assets to maximum (`type(uint256).max`).", - "params": { - "_maximumTotalAssets": "New value of the maximum total assets amount. It is the maximum amount of the tBTC token that the Acre protocol can hold.", - "_minimumDepositAmount": "New value of the minimum deposit amount. It is the minimum amount for a single deposit operation." - } - }, - "updateDispatcher(address)": { - "params": { - "newDispatcher": "Address of the new dispatcher contract." - } - }, - "updateEntryFeeBasisPoints(uint256)": { - "params": { - "newEntryFeeBasisPoints": "New value of the fee basis points." - } - }, - "updateTreasury(address)": { - "params": { - "newTreasury": "New treasury wallet address." - } - }, - "withdraw(uint256,address,address)": { - "details": "See {IERC4626-withdraw}. " - } - }, - "title": "stBTC", - "version": 1 - }, - "userdoc": { - "errors": { - "DisallowedAddress()": [ - { - "notice": "Reverts if the address is disallowed." - } - ], - "LessThanMinDeposit(uint256,uint256)": [ - { - "notice": "Reverts if the amount is less than the minimum deposit amount." - } - ], - "ZeroAddress()": [ - { - "notice": "Reverts if the address is zero." - } - ] - }, - "events": { - "DepositParametersUpdated(uint256,uint256)": { - "notice": "Emitted when deposit parameters are updated." - }, - "DispatcherUpdated(address,address)": { - "notice": "Emitted when the dispatcher contract is updated." - }, - "EntryFeeBasisPointsUpdated(uint256)": { - "notice": "Emitted when the entry fee basis points are updated." - }, - "StakeReferral(uint16,uint256)": { - "notice": "Emitted when a referral is used." - }, - "TreasuryUpdated(address)": { - "notice": "Emitted when the treasury wallet address is updated." - } - }, - "kind": "user", - "methods": { - "deposit(uint256,address)": { - "notice": "Mints shares to receiver by depositing exactly amount of tBTC tokens." - }, - "dispatcher()": { - "notice": "Dispatcher contract that routes tBTC from stBTC to a given vault and back." - }, - "entryFeeBasisPoints()": { - "notice": "Entry fee basis points applied to entry fee calculation." - }, - "maxDeposit(address)": { - "notice": "Returns the maximum amount of the tBTC token that can be deposited into the vault for the receiver through a deposit call. It takes into account the deposit parameter, maximum total assets, which determines the total amount of tBTC token held by Acre. This function always returns available limit for deposits, but the fee is not taken into account. As a result of this, there always will be some dust left. If the dust is lower than the minimum deposit amount, this function will return 0." - }, - "maxMint(address)": { - "notice": "Returns the maximum amount of the vault shares that can be minted for the receiver, through a mint call." - }, - "maximumTotalAssets()": { - "notice": "Maximum total amount of tBTC token held by Acre protocol." - }, - "minimumDepositAmount()": { - "notice": "Minimum amount for a single deposit operation. The value should be set low enough so the deposits routed through TbtcDepositor contract won't be rejected. It means that minimumDepositAmount should be lower than tBTC protocol's depositDustThreshold reduced by all the minting fees taken before depositing in the Acre contract." - }, - "mint(uint256,address)": { - "notice": "Mints shares to receiver by depositing tBTC tokens." - }, - "stake(uint256,address,uint16)": { - "notice": "Stakes a given amount of tBTC token and mints shares to a receiver." - }, - "treasury()": { - "notice": "Address of the treasury wallet, where fees should be transferred to." - }, - "updateDepositParameters(uint256,uint256)": { - "notice": "Updates deposit parameters." - }, - "updateDispatcher(address)": { - "notice": "Updates the dispatcher contract and gives it an unlimited allowance to transfer staked tBTC." - }, - "updateEntryFeeBasisPoints(uint256)": { - "notice": "Update the entry fee basis points." - }, - "updateTreasury(address)": { - "notice": "Updates treasury wallet address." - } - }, - "notice": "This contract implements the ERC-4626 tokenized vault standard. By staking tBTC, users acquire a liquid staking token called stBTC, commonly referred to as \"shares\". The staked tBTC is securely deposited into Acre's vaults, where it generates yield over time. Users have the flexibility to redeem stBTC, enabling them to withdraw their staked tBTC along with the accrued yield.", - "version": 1 - }, - "storageLayout": { - "storage": [ - { - "astId": 4066, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_balances", - "offset": 0, - "slot": "0", - "type": "t_mapping(t_address,t_uint256)" - }, - { - "astId": 4072, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_allowances", - "offset": 0, - "slot": "1", - "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" - }, - { - "astId": 4074, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_totalSupply", - "offset": 0, - "slot": "2", - "type": "t_uint256" - }, - { - "astId": 4076, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_name", - "offset": 0, - "slot": "3", - "type": "t_string_storage" - }, - { - "astId": 4078, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_symbol", - "offset": 0, - "slot": "4", - "type": "t_string_storage" - }, - { - "astId": 3597, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_owner", - "offset": 0, - "slot": "5", - "type": "t_address" - }, - { - "astId": 8071, - "contract": "contracts/stBTC.sol:stBTC", - "label": "dispatcher", - "offset": 0, - "slot": "6", - "type": "t_contract(Dispatcher)7334" - }, - { - "astId": 8074, - "contract": "contracts/stBTC.sol:stBTC", - "label": "treasury", - "offset": 0, - "slot": "7", - "type": "t_address" - }, - { - "astId": 8077, - "contract": "contracts/stBTC.sol:stBTC", - "label": "entryFeeBasisPoints", - "offset": 0, - "slot": "8", - "type": "t_uint256" - }, - { - "astId": 8080, - "contract": "contracts/stBTC.sol:stBTC", - "label": "minimumDepositAmount", - "offset": 0, - "slot": "9", - "type": "t_uint256" - }, - { - "astId": 8083, - "contract": "contracts/stBTC.sol:stBTC", - "label": "maximumTotalAssets", - "offset": 0, - "slot": "10", - "type": "t_uint256" - } - ], - "types": { - "t_address": { - "encoding": "inplace", - "label": "address", - "numberOfBytes": "20" - }, - "t_contract(Dispatcher)7334": { - "encoding": "inplace", - "label": "contract Dispatcher", - "numberOfBytes": "20" - }, - "t_mapping(t_address,t_mapping(t_address,t_uint256))": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => mapping(address => uint256))", - "numberOfBytes": "32", - "value": "t_mapping(t_address,t_uint256)" - }, - "t_mapping(t_address,t_uint256)": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => uint256)", - "numberOfBytes": "32", - "value": "t_uint256" - }, - "t_string_storage": { - "encoding": "bytes", - "label": "string", - "numberOfBytes": "32" - }, - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - } - } - } + "implementation": "0x5e6A8368005AD055590AB8C7f9DB6f9f6860f634", + "devdoc": "Contract deployed as upgradable proxy" } \ No newline at end of file From ad6116a3a8f0916ac542b487e971b3a57a7ee60c Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Thu, 11 Apr 2024 18:21:11 +0200 Subject: [PATCH 067/110] Increase wait time for sepolia deployment --- solidity/helpers/deployment.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/solidity/helpers/deployment.ts b/solidity/helpers/deployment.ts index bb1d68999..da80b3fef 100644 --- a/solidity/helpers/deployment.ts +++ b/solidity/helpers/deployment.ts @@ -15,7 +15,7 @@ export function waitConfirmationsNumber( switch (hre.network.name) { case "mainnet": case "sepolia": - return 2 + return 6 default: return 1 } From df6e96aa1e7d266e451c3f5bb5464cd1ce157ce7 Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Thu, 11 Apr 2024 18:22:39 +0200 Subject: [PATCH 068/110] Update contracts artifacts import We don't need to duplicate the contracts artifacts by copying them to SDK module, we can import them from the contracts module. --- .../artifacts/sepolia/BitcoinDepositor.json | 1337 -------------- .../lib/ethereum/artifacts/sepolia/stBTC.json | 1642 ----------------- sdk/src/lib/ethereum/bitcoin-depositor.ts | 4 +- sdk/src/lib/ethereum/stbtc.ts | 3 +- 4 files changed, 4 insertions(+), 2982 deletions(-) delete mode 100644 sdk/src/lib/ethereum/artifacts/sepolia/BitcoinDepositor.json delete mode 100644 sdk/src/lib/ethereum/artifacts/sepolia/stBTC.json diff --git a/sdk/src/lib/ethereum/artifacts/sepolia/BitcoinDepositor.json b/sdk/src/lib/ethereum/artifacts/sepolia/BitcoinDepositor.json deleted file mode 100644 index c09f41dfd..000000000 --- a/sdk/src/lib/ethereum/artifacts/sepolia/BitcoinDepositor.json +++ /dev/null @@ -1,1337 +0,0 @@ -{ - "address": "0x37E34EbC743FFAf96b56b3f62854bb7E733a4B50", - "abi": [ - { - "inputs": [ - { - "internalType": "address", - "name": "bridge", - "type": "address" - }, - { - "internalType": "address", - "name": "tbtcVault", - "type": "address" - }, - { - "internalType": "address", - "name": "_tbtcToken", - "type": "address" - }, - { - "internalType": "address", - "name": "_stbtc", - "type": "address" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "target", - "type": "address" - } - ], - "name": "AddressEmptyCode", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "AddressInsufficientBalance", - "type": "error" - }, - { - "inputs": [], - "name": "BridgingCompletionAlreadyNotified", - "type": "error" - }, - { - "inputs": [], - "name": "BridgingFinalizationAlreadyCalled", - "type": "error" - }, - { - "inputs": [], - "name": "BridgingNotCompleted", - "type": "error" - }, - { - "inputs": [], - "name": "CallerNotStaker", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "depositorFee", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "bridgedAmount", - "type": "uint256" - } - ], - "name": "DepositorFeeExceedsBridgedAmount", - "type": "error" - }, - { - "inputs": [], - "name": "FailedInnerCall", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "amountToStake", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "currentBalance", - "type": "uint256" - } - ], - "name": "InsufficientTbtcBalance", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - } - ], - "name": "OwnableInvalidOwner", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "OwnableUnauthorizedAccount", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "uint8", - "name": "bits", - "type": "uint8" - }, - { - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "SafeCastOverflowedUintDowncast", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - } - ], - "name": "SafeERC20FailedOperation", - "type": "error" - }, - { - "inputs": [], - "name": "StakeRequestNotQueued", - "type": "error" - }, - { - "inputs": [], - "name": "StakerIsZeroAddress", - "type": "error" - }, - { - "inputs": [], - "name": "StbtcZeroAddress", - "type": "error" - }, - { - "inputs": [], - "name": "TbtcTokenZeroAddress", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "enum AcreBitcoinDepositor.StakeRequestState", - "name": "currentState", - "type": "uint8" - }, - { - "internalType": "enum AcreBitcoinDepositor.StakeRequestState", - "name": "expectedState", - "type": "uint8" - } - ], - "name": "UnexpectedStakeRequestState", - "type": "error" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, - { - "indexed": true, - "internalType": "address", - "name": "caller", - "type": "address" - }, - { - "indexed": true, - "internalType": "uint16", - "name": "referral", - "type": "uint16" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "bridgedAmount", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "depositorFee", - "type": "uint256" - } - ], - "name": "BridgingCompleted", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "tbtcAmount", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint32", - "name": "finalizedAt", - "type": "uint32" - } - ], - "name": "DepositFinalized", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint32", - "name": "initializedAt", - "type": "uint32" - } - ], - "name": "DepositInitialized", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint64", - "name": "depositorFeeDivisor", - "type": "uint64" - } - ], - "name": "DepositorFeeDivisorUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "previousOwner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "OwnershipTransferStarted", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "previousOwner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "OwnershipTransferred", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, - { - "indexed": true, - "internalType": "address", - "name": "staker", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "amountToStake", - "type": "uint256" - } - ], - "name": "StakeRequestCancelledFromQueue", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, - { - "indexed": true, - "internalType": "address", - "name": "caller", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "stakedAmount", - "type": "uint256" - } - ], - "name": "StakeRequestFinalized", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, - { - "indexed": true, - "internalType": "address", - "name": "caller", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "stakedAmount", - "type": "uint256" - } - ], - "name": "StakeRequestFinalizedFromQueue", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, - { - "indexed": true, - "internalType": "address", - "name": "caller", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "staker", - "type": "address" - } - ], - "name": "StakeRequestInitialized", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - }, - { - "indexed": true, - "internalType": "address", - "name": "caller", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "queuedAmount", - "type": "uint256" - } - ], - "name": "StakeRequestQueued", - "type": "event" - }, - { - "inputs": [], - "name": "SATOSHI_MULTIPLIER", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "acceptOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "bridge", - "outputs": [ - { - "internalType": "contract IBridge", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - } - ], - "name": "cancelQueuedStake", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "bytes32", - "name": "extraData", - "type": "bytes32" - } - ], - "name": "decodeExtraData", - "outputs": [ - { - "internalType": "address", - "name": "staker", - "type": "address" - }, - { - "internalType": "uint16", - "name": "referral", - "type": "uint16" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [], - "name": "depositorFeeDivisor", - "outputs": [ - { - "internalType": "uint64", - "name": "", - "type": "uint64" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "staker", - "type": "address" - }, - { - "internalType": "uint16", - "name": "referral", - "type": "uint16" - } - ], - "name": "encodeExtraData", - "outputs": [ - { - "internalType": "bytes32", - "name": "", - "type": "bytes32" - } - ], - "stateMutability": "pure", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - } - ], - "name": "finalizeQueuedStake", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - } - ], - "name": "finalizeStake", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "components": [ - { - "internalType": "bytes4", - "name": "version", - "type": "bytes4" - }, - { - "internalType": "bytes", - "name": "inputVector", - "type": "bytes" - }, - { - "internalType": "bytes", - "name": "outputVector", - "type": "bytes" - }, - { - "internalType": "bytes4", - "name": "locktime", - "type": "bytes4" - } - ], - "internalType": "struct IBridgeTypes.BitcoinTxInfo", - "name": "fundingTx", - "type": "tuple" - }, - { - "components": [ - { - "internalType": "uint32", - "name": "fundingOutputIndex", - "type": "uint32" - }, - { - "internalType": "bytes8", - "name": "blindingFactor", - "type": "bytes8" - }, - { - "internalType": "bytes20", - "name": "walletPubKeyHash", - "type": "bytes20" - }, - { - "internalType": "bytes20", - "name": "refundPubKeyHash", - "type": "bytes20" - }, - { - "internalType": "bytes4", - "name": "refundLocktime", - "type": "bytes4" - }, - { - "internalType": "address", - "name": "vault", - "type": "address" - } - ], - "internalType": "struct IBridgeTypes.DepositRevealInfo", - "name": "reveal", - "type": "tuple" - }, - { - "internalType": "address", - "name": "staker", - "type": "address" - }, - { - "internalType": "uint16", - "name": "referral", - "type": "uint16" - } - ], - "name": "initializeStake", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "owner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "pendingOwner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "depositKey", - "type": "uint256" - } - ], - "name": "queueStake", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "renounceOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "name": "stakeRequests", - "outputs": [ - { - "internalType": "enum AcreBitcoinDepositor.StakeRequestState", - "name": "state", - "type": "uint8" - }, - { - "internalType": "address", - "name": "staker", - "type": "address" - }, - { - "internalType": "uint88", - "name": "queuedAmount", - "type": "uint88" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "stbtc", - "outputs": [ - { - "internalType": "contract stBTC", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "tbtcToken", - "outputs": [ - { - "internalType": "contract IERC20", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "tbtcVault", - "outputs": [ - { - "internalType": "contract ITBTCVault", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "transferOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint64", - "name": "newDepositorFeeDivisor", - "type": "uint64" - } - ], - "name": "updateDepositorFeeDivisor", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } - ], - "transactionHash": "0x6f7d1a83200314126aa36f4aaac2450d2a0c1ffd77a53327d35bf6c0331d4bec", - "receipt": { - "to": null, - "from": "0x2d154A5c7cE9939274b89bbCe9f5B069E57b09A8", - "contractAddress": "0x37E34EbC743FFAf96b56b3f62854bb7E733a4B50", - "transactionIndex": 157, - "gasUsed": "2013605", - "logsBloom": "0x00000000000000000000000000000000000000000000000000800000000000000002000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000001000000000000000000000000000000400000020000000000000000000800000000000000000000000000000000400000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000012000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0x13e2258b7e01b5bb7b0c5d438c0e623c89056660447e4bff2cd8a812392a6df5", - "transactionHash": "0x6f7d1a83200314126aa36f4aaac2450d2a0c1ffd77a53327d35bf6c0331d4bec", - "logs": [ - { - "transactionIndex": 157, - "blockNumber": 5387080, - "transactionHash": "0x6f7d1a83200314126aa36f4aaac2450d2a0c1ffd77a53327d35bf6c0331d4bec", - "address": "0x37E34EbC743FFAf96b56b3f62854bb7E733a4B50", - "topics": [ - "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", - "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x0000000000000000000000002d154a5c7ce9939274b89bbce9f5b069e57b09a8" - ], - "data": "0x", - "logIndex": 237, - "blockHash": "0x13e2258b7e01b5bb7b0c5d438c0e623c89056660447e4bff2cd8a812392a6df5" - } - ], - "blockNumber": 5387080, - "cumulativeGasUsed": "27025873", - "status": 1, - "byzantium": true - }, - "args": [ - "0x9b1a7fE5a16A15F2f9475C5B231750598b113403", - "0xB5679dE944A79732A75CE556191DF11F489448d5", - "0x517f2982701695D4E52f1ECFBEf3ba31Df470161", - "0xF99139f09164B092bD9e8558984Becfb0d2eCb87" - ], - "numDeployments": 1, - "solcInputHash": "49f0432287e96a47d66ba17ae7bf5d96", - "metadata": "{\"compiler\":{\"version\":\"0.8.21+commit.d9974bed\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"bridge\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"tbtcVault\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_tbtcToken\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_stbtc\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"}],\"name\":\"AddressEmptyCode\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"AddressInsufficientBalance\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"BridgingCompletionAlreadyNotified\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"BridgingFinalizationAlreadyCalled\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"BridgingNotCompleted\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"CallerNotStaker\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"depositorFee\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"bridgedAmount\",\"type\":\"uint256\"}],\"name\":\"DepositorFeeExceedsBridgedAmount\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"FailedInnerCall\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amountToStake\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"currentBalance\",\"type\":\"uint256\"}],\"name\":\"InsufficientTbtcBalance\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"OwnableInvalidOwner\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"OwnableUnauthorizedAccount\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint8\",\"name\":\"bits\",\"type\":\"uint8\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"SafeCastOverflowedUintDowncast\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"SafeERC20FailedOperation\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"StakeRequestNotQueued\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"StakerIsZeroAddress\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"StbtcZeroAddress\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"TbtcTokenZeroAddress\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"enum AcreBitcoinDepositor.StakeRequestState\",\"name\":\"currentState\",\"type\":\"uint8\"},{\"internalType\":\"enum AcreBitcoinDepositor.StakeRequestState\",\"name\":\"expectedState\",\"type\":\"uint8\"}],\"name\":\"UnexpectedStakeRequestState\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint16\",\"name\":\"referral\",\"type\":\"uint16\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"bridgedAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"depositorFee\",\"type\":\"uint256\"}],\"name\":\"BridgingCompleted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"tbtcAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"finalizedAt\",\"type\":\"uint32\"}],\"name\":\"DepositFinalized\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint32\",\"name\":\"initializedAt\",\"type\":\"uint32\"}],\"name\":\"DepositInitialized\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint64\",\"name\":\"depositorFeeDivisor\",\"type\":\"uint64\"}],\"name\":\"DepositorFeeDivisorUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferStarted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amountToStake\",\"type\":\"uint256\"}],\"name\":\"StakeRequestCancelledFromQueue\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"stakedAmount\",\"type\":\"uint256\"}],\"name\":\"StakeRequestFinalized\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"stakedAmount\",\"type\":\"uint256\"}],\"name\":\"StakeRequestFinalizedFromQueue\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"}],\"name\":\"StakeRequestInitialized\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"caller\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"queuedAmount\",\"type\":\"uint256\"}],\"name\":\"StakeRequestQueued\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"SATOSHI_MULTIPLIER\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"acceptOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"bridge\",\"outputs\":[{\"internalType\":\"contract IBridge\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"}],\"name\":\"cancelQueuedStake\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"extraData\",\"type\":\"bytes32\"}],\"name\":\"decodeExtraData\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"},{\"internalType\":\"uint16\",\"name\":\"referral\",\"type\":\"uint16\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"depositorFeeDivisor\",\"outputs\":[{\"internalType\":\"uint64\",\"name\":\"\",\"type\":\"uint64\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"},{\"internalType\":\"uint16\",\"name\":\"referral\",\"type\":\"uint16\"}],\"name\":\"encodeExtraData\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"}],\"name\":\"finalizeQueuedStake\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"}],\"name\":\"finalizeStake\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"bytes4\",\"name\":\"version\",\"type\":\"bytes4\"},{\"internalType\":\"bytes\",\"name\":\"inputVector\",\"type\":\"bytes\"},{\"internalType\":\"bytes\",\"name\":\"outputVector\",\"type\":\"bytes\"},{\"internalType\":\"bytes4\",\"name\":\"locktime\",\"type\":\"bytes4\"}],\"internalType\":\"struct IBridgeTypes.BitcoinTxInfo\",\"name\":\"fundingTx\",\"type\":\"tuple\"},{\"components\":[{\"internalType\":\"uint32\",\"name\":\"fundingOutputIndex\",\"type\":\"uint32\"},{\"internalType\":\"bytes8\",\"name\":\"blindingFactor\",\"type\":\"bytes8\"},{\"internalType\":\"bytes20\",\"name\":\"walletPubKeyHash\",\"type\":\"bytes20\"},{\"internalType\":\"bytes20\",\"name\":\"refundPubKeyHash\",\"type\":\"bytes20\"},{\"internalType\":\"bytes4\",\"name\":\"refundLocktime\",\"type\":\"bytes4\"},{\"internalType\":\"address\",\"name\":\"vault\",\"type\":\"address\"}],\"internalType\":\"struct IBridgeTypes.DepositRevealInfo\",\"name\":\"reveal\",\"type\":\"tuple\"},{\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"},{\"internalType\":\"uint16\",\"name\":\"referral\",\"type\":\"uint16\"}],\"name\":\"initializeStake\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pendingOwner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"depositKey\",\"type\":\"uint256\"}],\"name\":\"queueStake\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"stakeRequests\",\"outputs\":[{\"internalType\":\"enum AcreBitcoinDepositor.StakeRequestState\",\"name\":\"state\",\"type\":\"uint8\"},{\"internalType\":\"address\",\"name\":\"staker\",\"type\":\"address\"},{\"internalType\":\"uint88\",\"name\":\"queuedAmount\",\"type\":\"uint88\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"stbtc\",\"outputs\":[{\"internalType\":\"contract stBTC\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"tbtcToken\",\"outputs\":[{\"internalType\":\"contract IERC20\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"tbtcVault\",\"outputs\":[{\"internalType\":\"contract ITBTCVault\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint64\",\"name\":\"newDepositorFeeDivisor\",\"type\":\"uint64\"}],\"name\":\"updateDepositorFeeDivisor\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"errors\":{\"AddressEmptyCode(address)\":[{\"details\":\"There's no code at `target` (it is not a contract).\"}],\"AddressInsufficientBalance(address)\":[{\"details\":\"The ETH balance of the account is not enough to perform the operation.\"}],\"BridgingCompletionAlreadyNotified()\":[{\"details\":\"Attempted to notify a bridging completion, while it was already notified.\"}],\"BridgingFinalizationAlreadyCalled()\":[{\"details\":\"Attempted to call bridging finalization for a stake request for which the function was already called.\"}],\"BridgingNotCompleted()\":[{\"details\":\"Attempted to finalize a stake request, while bridging completion has not been notified yet.\"}],\"CallerNotStaker()\":[{\"details\":\"Attempted to call function by an account that is not the staker.\"}],\"DepositorFeeExceedsBridgedAmount(uint256,uint256)\":[{\"details\":\"Calculated depositor fee exceeds the amount of minted tBTC tokens.\"}],\"FailedInnerCall()\":[{\"details\":\"A call to an address target failed. The target may have reverted.\"}],\"InsufficientTbtcBalance(uint256,uint256)\":[{\"details\":\"Attempted to finalize bridging with depositor's contract tBTC balance lower than the calculated bridged tBTC amount. This error means that Governance should top-up the tBTC reserve for bridging fees approximation.\"}],\"OwnableInvalidOwner(address)\":[{\"details\":\"The owner is not a valid owner account. (eg. `address(0)`)\"}],\"OwnableUnauthorizedAccount(address)\":[{\"details\":\"The caller account is not authorized to perform an operation.\"}],\"SafeCastOverflowedUintDowncast(uint8,uint256)\":[{\"details\":\"Value doesn't fit in an uint of `bits` size.\"}],\"SafeERC20FailedOperation(address)\":[{\"details\":\"An operation with an ERC20 token failed.\"}],\"StakeRequestNotQueued()\":[{\"details\":\"Attempted to finalize or cancel a stake request that was not added to the queue, or was already finalized or cancelled.\"}],\"StakerIsZeroAddress()\":[{\"details\":\"Staker address is zero.\"}],\"UnexpectedStakeRequestState(uint8,uint8)\":[{\"details\":\"Attempted to execute function for stake request in unexpected current state.\"}]},\"events\":{\"BridgingCompleted(uint256,address,uint16,uint256,uint256)\":{\"params\":{\"bridgedAmount\":\"Amount of tBTC tokens that was bridged by the tBTC bridge.\",\"caller\":\"Address that notified about bridging completion.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"depositorFee\":\"Depositor fee amount.\",\"referral\":\"Identifier of a partner in the referral program.\"}},\"DepositorFeeDivisorUpdated(uint64)\":{\"params\":{\"depositorFeeDivisor\":\"New value of the depositor fee divisor.\"}},\"StakeRequestCancelledFromQueue(uint256,address,uint256)\":{\"params\":{\"amountToStake\":\"Amount of queued tBTC tokens that got cancelled.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"staker\":\"Address of the staker.\"}},\"StakeRequestFinalized(uint256,address,uint256)\":{\"details\":\"Deposit details can be fetched from {{ ERC4626.Deposit }} event emitted in the same transaction.\",\"params\":{\"caller\":\"Address that finalized the stake request.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"stakedAmount\":\"Amount of staked tBTC tokens.\"}},\"StakeRequestFinalizedFromQueue(uint256,address,uint256)\":{\"details\":\"Deposit details can be fetched from {{ ERC4626.Deposit }} event emitted in the same transaction.\",\"params\":{\"caller\":\"Address that finalized the stake request.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"stakedAmount\":\"Amount of staked tBTC tokens.\"}},\"StakeRequestInitialized(uint256,address,address)\":{\"details\":\"Deposit details can be fetched from {{ Bridge.DepositRevealed }} event emitted in the same transaction.\",\"params\":{\"caller\":\"Address that initialized the stake request.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"staker\":\"The address to which the stBTC shares will be minted.\"}},\"StakeRequestQueued(uint256,address,uint256)\":{\"params\":{\"caller\":\"Address that finalized the stake request.\",\"depositKey\":\"Deposit key identifying the deposit.\",\"queuedAmount\":\"Amount of queued tBTC tokens.\"}}},\"kind\":\"dev\",\"methods\":{\"acceptOwnership()\":{\"details\":\"The new owner accepts the ownership transfer.\"},\"cancelQueuedStake(uint256)\":{\"details\":\"This function can be called only after the stake request was added to queue.Only staker provided in the extra data of the stake request can call this function.\",\"params\":{\"depositKey\":\"Deposit key identifying the deposit.\"}},\"constructor\":{\"params\":{\"_stbtc\":\"stBTC contract instance.\",\"_tbtcToken\":\"tBTC token contract instance.\",\"bridge\":\"tBTC Bridge contract instance.\",\"tbtcVault\":\"tBTC Vault contract instance.\"}},\"decodeExtraData(bytes32)\":{\"details\":\"Unpacks the data from bytes32: 20 bytes of staker address and 2 bytes of referral, 10 bytes of trailing zeros.\",\"params\":{\"extraData\":\"Encoded extra data.\"},\"returns\":{\"referral\":\"Data used for referral program.\",\"staker\":\"The address to which the stBTC shares will be minted.\"}},\"encodeExtraData(address,uint16)\":{\"details\":\"Packs the data to bytes32: 20 bytes of staker address and 2 bytes of referral, 10 bytes of trailing zeros.\",\"params\":{\"referral\":\"Data used for referral program.\",\"staker\":\"The address to which the stBTC shares will be minted.\"},\"returns\":{\"_0\":\"Encoded extra data.\"}},\"finalizeQueuedStake(uint256)\":{\"params\":{\"depositKey\":\"Deposit key identifying the deposit.\"}},\"finalizeStake(uint256)\":{\"details\":\"In case depositing in stBTC vault fails (e.g. because of the maximum deposit limit being reached), the `queueStake` function should be called to add the stake request to the staking queue.\",\"params\":{\"depositKey\":\"Deposit key identifying the deposit.\"}},\"initializeStake((bytes4,bytes,bytes,bytes4),(uint32,bytes8,bytes20,bytes20,bytes4,address),address,uint16)\":{\"details\":\"Requirements: - The revealed vault address must match the TBTCVault address, - All requirements from {Bridge#revealDepositWithExtraData} function must be met. - `staker` must be the staker address used in the P2(W)SH BTC deposit transaction as part of the extra data. - `referral` must be the referral info used in the P2(W)SH BTC deposit transaction as part of the extra data. - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex` can be revealed only one time.\",\"params\":{\"fundingTx\":\"Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.\",\"referral\":\"Data used for referral program.\",\"reveal\":\"Deposit reveal data, see `IBridgeTypes.DepositRevealInfo`.\",\"staker\":\"The address to which the stBTC shares will be minted.\"}},\"owner()\":{\"details\":\"Returns the address of the current owner.\"},\"pendingOwner()\":{\"details\":\"Returns the address of the pending owner.\"},\"queueStake(uint256)\":{\"details\":\"It queues the stake request, until the stBTC vault is ready to accept the deposit. The request must be finalized with `finalizeQueuedStake` after the limit is increased or other user withdraws their funds from the stBTC contract to make place for another deposit. The staker has a possibility to submit `cancelQueuedStake` that will withdraw the minted tBTC token and abort staking process.\",\"params\":{\"depositKey\":\"Deposit key identifying the deposit.\"}},\"renounceOwnership()\":{\"details\":\"Leaves the contract without owner. It will not be possible to call `onlyOwner` functions. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby disabling any functionality that is only available to the owner.\"},\"transferOwnership(address)\":{\"details\":\"Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. Can only be called by the current owner.\"},\"updateDepositorFeeDivisor(uint64)\":{\"params\":{\"newDepositorFeeDivisor\":\"New depositor fee divisor value.\"}}},\"stateVariables\":{\"depositorFeeDivisor\":{\"details\":\"That fee is computed as follows: `depositorFee = depositedAmount / depositorFeeDivisor` for example, if the depositor fee needs to be 2% of each deposit, the `depositorFeeDivisor` should be set to `50` because `1/50 = 0.02 = 2%`.\"},\"stakeRequests\":{\"details\":\"The key is a deposit key identifying the deposit.\"}},\"title\":\"Acre Bitcoin Depositor contract.\",\"version\":1},\"userdoc\":{\"errors\":{\"StbtcZeroAddress()\":[{\"notice\":\"Reverts if the stBTC address is zero.\"}],\"TbtcTokenZeroAddress()\":[{\"notice\":\"Reverts if the tBTC Token address is zero.\"}]},\"events\":{\"BridgingCompleted(uint256,address,uint16,uint256,uint256)\":{\"notice\":\"Emitted when bridging completion has been notified.\"},\"DepositorFeeDivisorUpdated(uint64)\":{\"notice\":\"Emitted when a depositor fee divisor is updated.\"},\"StakeRequestCancelledFromQueue(uint256,address,uint256)\":{\"notice\":\"Emitted when a queued stake request is cancelled.\"},\"StakeRequestFinalized(uint256,address,uint256)\":{\"notice\":\"Emitted when a stake request is finalized.\"},\"StakeRequestFinalizedFromQueue(uint256,address,uint256)\":{\"notice\":\"Emitted when a stake request is finalized from the queue.\"},\"StakeRequestInitialized(uint256,address,address)\":{\"notice\":\"Emitted when a stake request is initialized.\"},\"StakeRequestQueued(uint256,address,uint256)\":{\"notice\":\"Emitted when a stake request is queued.\"}},\"kind\":\"user\",\"methods\":{\"SATOSHI_MULTIPLIER()\":{\"notice\":\"Multiplier to convert satoshi to TBTC token units.\"},\"bridge()\":{\"notice\":\"Bridge contract address.\"},\"cancelQueuedStake(uint256)\":{\"notice\":\"Cancel queued stake. The function can be called by the staker to recover tBTC that cannot be finalized to stake in stBTC contract due to a deposit limit being reached.\"},\"constructor\":{\"notice\":\"Acre Bitcoin Depositor contract constructor.\"},\"decodeExtraData(bytes32)\":{\"notice\":\"Decodes staker address and referral from extra data.\"},\"depositorFeeDivisor()\":{\"notice\":\"Divisor used to compute the depositor fee taken from each deposit and transferred to the treasury upon stake request finalization.\"},\"encodeExtraData(address,uint16)\":{\"notice\":\"Encodes staker address and referral as extra data.\"},\"finalizeQueuedStake(uint256)\":{\"notice\":\"This function should be called for previously queued stake request, when stBTC vault is able to accept a deposit.\"},\"finalizeStake(uint256)\":{\"notice\":\"This function should be called for previously initialized stake request, after tBTC bridging process was finalized. It stakes the tBTC from the given deposit into stBTC, emitting the stBTC shares to the staker specified in the deposit extra data and using the referral provided in the extra data.\"},\"initializeStake((bytes4,bytes,bytes,bytes4),(uint32,bytes8,bytes20,bytes20,bytes4,address),address,uint16)\":{\"notice\":\"This function allows staking process initialization for a Bitcoin deposit made by an user with a P2(W)SH transaction. It uses the supplied information to reveal a deposit to the tBTC Bridge contract.\"},\"queueStake(uint256)\":{\"notice\":\"This function should be called for previously initialized stake request, after tBTC bridging process was finalized, in case the `finalizeStake` failed due to stBTC vault deposit limit being reached.\"},\"stakeRequests(uint256)\":{\"notice\":\"Mapping of stake requests.\"},\"stbtc()\":{\"notice\":\"stBTC contract.\"},\"tbtcToken()\":{\"notice\":\"tBTC Token contract.\"},\"tbtcVault()\":{\"notice\":\"TBTCVault contract address.\"},\"updateDepositorFeeDivisor(uint64)\":{\"notice\":\"Updates the depositor fee divisor.\"}},\"notice\":\"The contract integrates Acre staking with tBTC minting. User who wants to stake BTC in Acre should submit a Bitcoin transaction to the most recently created off-chain ECDSA wallets of the tBTC Bridge using pay-to-script-hash (P2SH) or pay-to-witness-script-hash (P2WSH) containing hashed information about this Depositor contract address, and staker's Ethereum address. Then, the staker initiates tBTC minting by revealing their Ethereum address along with their deposit blinding factor, refund public key hash and refund locktime on the tBTC Bridge through this Depositor contract. The off-chain ECDSA wallet and Optimistic Minting bots listen for these sorts of messages and when they get one, they check the Bitcoin network to make sure the deposit lines up. Majority of tBTC minting is finalized by the Optimistic Minting process, where Minter bot initializes minting process and if there is no veto from the Guardians, the process is finalized and tBTC minted to the Depositor address. If the revealed deposit is not handled by the Optimistic Minting process the off-chain ECDSA wallet may decide to pick the deposit transaction for sweeping, and when the sweep operation is confirmed on the Bitcoin network, the tBTC Bridge and tBTC vault mint the tBTC token to the Depositor address. After tBTC is minted to the Depositor, on the stake finalization tBTC is staked in stBTC contract and stBTC shares are emitted to the staker.\",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/AcreBitcoinDepositor.sol\":\"AcreBitcoinDepositor\"},\"evmVersion\":\"paris\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":1000},\"remappings\":[]},\"sources\":{\"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\":{\"content\":\"pragma solidity ^0.8.4;\\n\\n/** @title BitcoinSPV */\\n/** @author Summa (https://summa.one) */\\n\\nimport {BytesLib} from \\\"./BytesLib.sol\\\";\\nimport {SafeMath} from \\\"./SafeMath.sol\\\";\\n\\nlibrary BTCUtils {\\n using BytesLib for bytes;\\n using SafeMath for uint256;\\n\\n // The target at minimum Difficulty. Also the target of the genesis block\\n uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000;\\n\\n uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds\\n uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks\\n\\n uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\\n\\n /* ***** */\\n /* UTILS */\\n /* ***** */\\n\\n /// @notice Determines the length of a VarInt in bytes\\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\\n /// @param _flag The first byte of a VarInt\\n /// @return The number of non-flag bytes in the VarInt\\n function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) {\\n return determineVarIntDataLengthAt(_flag, 0);\\n }\\n\\n /// @notice Determines the length of a VarInt in bytes\\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\\n /// @param _b The byte array containing a VarInt\\n /// @param _at The position of the VarInt in the array\\n /// @return The number of non-flag bytes in the VarInt\\n function determineVarIntDataLengthAt(bytes memory _b, uint256 _at) internal pure returns (uint8) {\\n if (uint8(_b[_at]) == 0xff) {\\n return 8; // one-byte flag, 8 bytes data\\n }\\n if (uint8(_b[_at]) == 0xfe) {\\n return 4; // one-byte flag, 4 bytes data\\n }\\n if (uint8(_b[_at]) == 0xfd) {\\n return 2; // one-byte flag, 2 bytes data\\n }\\n\\n return 0; // flag is data\\n }\\n\\n /// @notice Parse a VarInt into its data length and the number it represents\\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\\n /// Caller SHOULD explicitly handle this case (or bubble it up)\\n /// @param _b A byte-string starting with a VarInt\\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\\n function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) {\\n return parseVarIntAt(_b, 0);\\n }\\n\\n /// @notice Parse a VarInt into its data length and the number it represents\\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\\n /// Caller SHOULD explicitly handle this case (or bubble it up)\\n /// @param _b A byte-string containing a VarInt\\n /// @param _at The position of the VarInt\\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\\n function parseVarIntAt(bytes memory _b, uint256 _at) internal pure returns (uint256, uint256) {\\n uint8 _dataLen = determineVarIntDataLengthAt(_b, _at);\\n\\n if (_dataLen == 0) {\\n return (0, uint8(_b[_at]));\\n }\\n if (_b.length < 1 + _dataLen + _at) {\\n return (ERR_BAD_ARG, 0);\\n }\\n uint256 _number;\\n if (_dataLen == 2) {\\n _number = reverseUint16(uint16(_b.slice2(1 + _at)));\\n } else if (_dataLen == 4) {\\n _number = reverseUint32(uint32(_b.slice4(1 + _at)));\\n } else if (_dataLen == 8) {\\n _number = reverseUint64(uint64(_b.slice8(1 + _at)));\\n }\\n return (_dataLen, _number);\\n }\\n\\n /// @notice Changes the endianness of a byte array\\n /// @dev Returns a new, backwards, bytes\\n /// @param _b The bytes to reverse\\n /// @return The reversed bytes\\n function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) {\\n bytes memory _newValue = new bytes(_b.length);\\n\\n for (uint i = 0; i < _b.length; i++) {\\n _newValue[_b.length - i - 1] = _b[i];\\n }\\n\\n return _newValue;\\n }\\n\\n /// @notice Changes the endianness of a uint256\\n /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel\\n /// @param _b The unsigned integer to reverse\\n /// @return v The reversed value\\n function reverseUint256(uint256 _b) internal pure returns (uint256 v) {\\n v = _b;\\n\\n // swap bytes\\n v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |\\n ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);\\n // swap 2-byte long pairs\\n v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |\\n ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);\\n // swap 4-byte long pairs\\n v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |\\n ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);\\n // swap 8-byte long pairs\\n v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |\\n ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);\\n // swap 16-byte long pairs\\n v = (v >> 128) | (v << 128);\\n }\\n\\n /// @notice Changes the endianness of a uint64\\n /// @param _b The unsigned integer to reverse\\n /// @return v The reversed value\\n function reverseUint64(uint64 _b) internal pure returns (uint64 v) {\\n v = _b;\\n\\n // swap bytes\\n v = ((v >> 8) & 0x00FF00FF00FF00FF) |\\n ((v & 0x00FF00FF00FF00FF) << 8);\\n // swap 2-byte long pairs\\n v = ((v >> 16) & 0x0000FFFF0000FFFF) |\\n ((v & 0x0000FFFF0000FFFF) << 16);\\n // swap 4-byte long pairs\\n v = (v >> 32) | (v << 32);\\n }\\n\\n /// @notice Changes the endianness of a uint32\\n /// @param _b The unsigned integer to reverse\\n /// @return v The reversed value\\n function reverseUint32(uint32 _b) internal pure returns (uint32 v) {\\n v = _b;\\n\\n // swap bytes\\n v = ((v >> 8) & 0x00FF00FF) |\\n ((v & 0x00FF00FF) << 8);\\n // swap 2-byte long pairs\\n v = (v >> 16) | (v << 16);\\n }\\n\\n /// @notice Changes the endianness of a uint24\\n /// @param _b The unsigned integer to reverse\\n /// @return v The reversed value\\n function reverseUint24(uint24 _b) internal pure returns (uint24 v) {\\n v = (_b << 16) | (_b & 0x00FF00) | (_b >> 16);\\n }\\n\\n /// @notice Changes the endianness of a uint16\\n /// @param _b The unsigned integer to reverse\\n /// @return v The reversed value\\n function reverseUint16(uint16 _b) internal pure returns (uint16 v) {\\n v = (_b << 8) | (_b >> 8);\\n }\\n\\n\\n /// @notice Converts big-endian bytes to a uint\\n /// @dev Traverses the byte array and sums the bytes\\n /// @param _b The big-endian bytes-encoded integer\\n /// @return The integer representation\\n function bytesToUint(bytes memory _b) internal pure returns (uint256) {\\n uint256 _number;\\n\\n for (uint i = 0; i < _b.length; i++) {\\n _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));\\n }\\n\\n return _number;\\n }\\n\\n /// @notice Get the last _num bytes from a byte array\\n /// @param _b The byte array to slice\\n /// @param _num The number of bytes to extract from the end\\n /// @return The last _num bytes of _b\\n function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) {\\n uint256 _start = _b.length.sub(_num);\\n\\n return _b.slice(_start, _num);\\n }\\n\\n /// @notice Implements bitcoin's hash160 (rmd160(sha2()))\\n /// @dev abi.encodePacked changes the return to bytes instead of bytes32\\n /// @param _b The pre-image\\n /// @return The digest\\n function hash160(bytes memory _b) internal pure returns (bytes memory) {\\n return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));\\n }\\n\\n /// @notice Implements bitcoin's hash160 (sha2 + ripemd160)\\n /// @dev sha2 precompile at address(2), ripemd160 at address(3)\\n /// @param _b The pre-image\\n /// @return res The digest\\n function hash160View(bytes memory _b) internal view returns (bytes20 res) {\\n // solium-disable-next-line security/no-inline-assembly\\n assembly {\\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\\n pop(staticcall(gas(), 3, 0x00, 32, 0x00, 32))\\n // read from position 12 = 0c\\n res := mload(0x0c)\\n }\\n }\\n\\n /// @notice Implements bitcoin's hash256 (double sha2)\\n /// @dev abi.encodePacked changes the return to bytes instead of bytes32\\n /// @param _b The pre-image\\n /// @return The digest\\n function hash256(bytes memory _b) internal pure returns (bytes32) {\\n return sha256(abi.encodePacked(sha256(_b)));\\n }\\n\\n /// @notice Implements bitcoin's hash256 (double sha2)\\n /// @dev sha2 is precompiled smart contract located at address(2)\\n /// @param _b The pre-image\\n /// @return res The digest\\n function hash256View(bytes memory _b) internal view returns (bytes32 res) {\\n // solium-disable-next-line security/no-inline-assembly\\n assembly {\\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\\n res := mload(0x00)\\n }\\n }\\n\\n /// @notice Implements bitcoin's hash256 on a pair of bytes32\\n /// @dev sha2 is precompiled smart contract located at address(2)\\n /// @param _a The first bytes32 of the pre-image\\n /// @param _b The second bytes32 of the pre-image\\n /// @return res The digest\\n function hash256Pair(bytes32 _a, bytes32 _b) internal view returns (bytes32 res) {\\n // solium-disable-next-line security/no-inline-assembly\\n assembly {\\n mstore(0x00, _a)\\n mstore(0x20, _b)\\n pop(staticcall(gas(), 2, 0x00, 64, 0x00, 32))\\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\\n res := mload(0x00)\\n }\\n }\\n\\n /// @notice Implements bitcoin's hash256 (double sha2)\\n /// @dev sha2 is precompiled smart contract located at address(2)\\n /// @param _b The array containing the pre-image\\n /// @param at The start of the pre-image\\n /// @param len The length of the pre-image\\n /// @return res The digest\\n function hash256Slice(\\n bytes memory _b,\\n uint256 at,\\n uint256 len\\n ) internal view returns (bytes32 res) {\\n // solium-disable-next-line security/no-inline-assembly\\n assembly {\\n pop(staticcall(gas(), 2, add(_b, add(32, at)), len, 0x00, 32))\\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\\n res := mload(0x00)\\n }\\n }\\n\\n /* ************ */\\n /* Legacy Input */\\n /* ************ */\\n\\n /// @notice Extracts the nth input from the vin (0-indexed)\\n /// @dev Iterates over the vin. If you need to extract several, write a custom function\\n /// @param _vin The vin as a tightly-packed byte array\\n /// @param _index The 0-indexed location of the input to extract\\n /// @return The input as a byte array\\n function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) {\\n uint256 _varIntDataLen;\\n uint256 _nIns;\\n\\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\\n require(_varIntDataLen != ERR_BAD_ARG, \\\"Read overrun during VarInt parsing\\\");\\n require(_index < _nIns, \\\"Vin read overrun\\\");\\n\\n uint256 _len = 0;\\n uint256 _offset = 1 + _varIntDataLen;\\n\\n for (uint256 _i = 0; _i < _index; _i ++) {\\n _len = determineInputLengthAt(_vin, _offset);\\n require(_len != ERR_BAD_ARG, \\\"Bad VarInt in scriptSig\\\");\\n _offset = _offset + _len;\\n }\\n\\n _len = determineInputLengthAt(_vin, _offset);\\n require(_len != ERR_BAD_ARG, \\\"Bad VarInt in scriptSig\\\");\\n return _vin.slice(_offset, _len);\\n }\\n\\n /// @notice Determines whether an input is legacy\\n /// @dev False if no scriptSig, otherwise True\\n /// @param _input The input\\n /// @return True for legacy, False for witness\\n function isLegacyInput(bytes memory _input) internal pure returns (bool) {\\n return _input[36] != hex\\\"00\\\";\\n }\\n\\n /// @notice Determines the length of a scriptSig in an input\\n /// @dev Will return 0 if passed a witness input.\\n /// @param _input The LEGACY input\\n /// @return The length of the script sig\\n function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) {\\n return extractScriptSigLenAt(_input, 0);\\n }\\n\\n /// @notice Determines the length of a scriptSig in an input\\n /// starting at the specified position\\n /// @dev Will return 0 if passed a witness input.\\n /// @param _input The byte array containing the LEGACY input\\n /// @param _at The position of the input in the array\\n /// @return The length of the script sig\\n function extractScriptSigLenAt(bytes memory _input, uint256 _at) internal pure returns (uint256, uint256) {\\n if (_input.length < 37 + _at) {\\n return (ERR_BAD_ARG, 0);\\n }\\n\\n uint256 _varIntDataLen;\\n uint256 _scriptSigLen;\\n (_varIntDataLen, _scriptSigLen) = parseVarIntAt(_input, _at + 36);\\n\\n return (_varIntDataLen, _scriptSigLen);\\n }\\n\\n /// @notice Determines the length of an input from its scriptSig\\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\\n /// @param _input The input\\n /// @return The length of the input in bytes\\n function determineInputLength(bytes memory _input) internal pure returns (uint256) {\\n return determineInputLengthAt(_input, 0);\\n }\\n\\n /// @notice Determines the length of an input from its scriptSig,\\n /// starting at the specified position\\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\\n /// @param _input The byte array containing the input\\n /// @param _at The position of the input in the array\\n /// @return The length of the input in bytes\\n function determineInputLengthAt(bytes memory _input, uint256 _at) internal pure returns (uint256) {\\n uint256 _varIntDataLen;\\n uint256 _scriptSigLen;\\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLenAt(_input, _at);\\n if (_varIntDataLen == ERR_BAD_ARG) {\\n return ERR_BAD_ARG;\\n }\\n\\n return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;\\n }\\n\\n /// @notice Extracts the LE sequence bytes from an input\\n /// @dev Sequence is used for relative time locks\\n /// @param _input The LEGACY input\\n /// @return The sequence bytes (LE uint)\\n function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes4) {\\n uint256 _varIntDataLen;\\n uint256 _scriptSigLen;\\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\\n require(_varIntDataLen != ERR_BAD_ARG, \\\"Bad VarInt in scriptSig\\\");\\n return _input.slice4(36 + 1 + _varIntDataLen + _scriptSigLen);\\n }\\n\\n /// @notice Extracts the sequence from the input\\n /// @dev Sequence is a 4-byte little-endian number\\n /// @param _input The LEGACY input\\n /// @return The sequence number (big-endian uint)\\n function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) {\\n uint32 _leSeqence = uint32(extractSequenceLELegacy(_input));\\n uint32 _beSequence = reverseUint32(_leSeqence);\\n return _beSequence;\\n }\\n /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx\\n /// @dev Will return hex\\\"00\\\" if passed a witness input\\n /// @param _input The LEGACY input\\n /// @return The length-prepended scriptSig\\n function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) {\\n uint256 _varIntDataLen;\\n uint256 _scriptSigLen;\\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\\n require(_varIntDataLen != ERR_BAD_ARG, \\\"Bad VarInt in scriptSig\\\");\\n return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);\\n }\\n\\n\\n /* ************* */\\n /* Witness Input */\\n /* ************* */\\n\\n /// @notice Extracts the LE sequence bytes from an input\\n /// @dev Sequence is used for relative time locks\\n /// @param _input The WITNESS input\\n /// @return The sequence bytes (LE uint)\\n function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes4) {\\n return _input.slice4(37);\\n }\\n\\n /// @notice Extracts the sequence from the input in a tx\\n /// @dev Sequence is a 4-byte little-endian number\\n /// @param _input The WITNESS input\\n /// @return The sequence number (big-endian uint)\\n function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) {\\n uint32 _leSeqence = uint32(extractSequenceLEWitness(_input));\\n uint32 _inputeSequence = reverseUint32(_leSeqence);\\n return _inputeSequence;\\n }\\n\\n /// @notice Extracts the outpoint from the input in a tx\\n /// @dev 32-byte tx id with 4-byte index\\n /// @param _input The input\\n /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)\\n function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) {\\n return _input.slice(0, 36);\\n }\\n\\n /// @notice Extracts the outpoint tx id from an input\\n /// @dev 32-byte tx id\\n /// @param _input The input\\n /// @return The tx id (little-endian bytes)\\n function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) {\\n return _input.slice32(0);\\n }\\n\\n /// @notice Extracts the outpoint tx id from an input\\n /// starting at the specified position\\n /// @dev 32-byte tx id\\n /// @param _input The byte array containing the input\\n /// @param _at The position of the input\\n /// @return The tx id (little-endian bytes)\\n function extractInputTxIdLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes32) {\\n return _input.slice32(_at);\\n }\\n\\n /// @notice Extracts the LE tx input index from the input in a tx\\n /// @dev 4-byte tx index\\n /// @param _input The input\\n /// @return The tx index (little-endian bytes)\\n function extractTxIndexLE(bytes memory _input) internal pure returns (bytes4) {\\n return _input.slice4(32);\\n }\\n\\n /// @notice Extracts the LE tx input index from the input in a tx\\n /// starting at the specified position\\n /// @dev 4-byte tx index\\n /// @param _input The byte array containing the input\\n /// @param _at The position of the input\\n /// @return The tx index (little-endian bytes)\\n function extractTxIndexLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes4) {\\n return _input.slice4(32 + _at);\\n }\\n\\n /* ****** */\\n /* Output */\\n /* ****** */\\n\\n /// @notice Determines the length of an output\\n /// @dev Works with any properly formatted output\\n /// @param _output The output\\n /// @return The length indicated by the prefix, error if invalid length\\n function determineOutputLength(bytes memory _output) internal pure returns (uint256) {\\n return determineOutputLengthAt(_output, 0);\\n }\\n\\n /// @notice Determines the length of an output\\n /// starting at the specified position\\n /// @dev Works with any properly formatted output\\n /// @param _output The byte array containing the output\\n /// @param _at The position of the output\\n /// @return The length indicated by the prefix, error if invalid length\\n function determineOutputLengthAt(bytes memory _output, uint256 _at) internal pure returns (uint256) {\\n if (_output.length < 9 + _at) {\\n return ERR_BAD_ARG;\\n }\\n uint256 _varIntDataLen;\\n uint256 _scriptPubkeyLength;\\n (_varIntDataLen, _scriptPubkeyLength) = parseVarIntAt(_output, 8 + _at);\\n\\n if (_varIntDataLen == ERR_BAD_ARG) {\\n return ERR_BAD_ARG;\\n }\\n\\n // 8-byte value, 1-byte for tag itself\\n return 8 + 1 + _varIntDataLen + _scriptPubkeyLength;\\n }\\n\\n /// @notice Extracts the output at a given index in the TxOuts vector\\n /// @dev Iterates over the vout. If you need to extract multiple, write a custom function\\n /// @param _vout The _vout to extract from\\n /// @param _index The 0-indexed location of the output to extract\\n /// @return The specified output\\n function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) {\\n uint256 _varIntDataLen;\\n uint256 _nOuts;\\n\\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\\n require(_varIntDataLen != ERR_BAD_ARG, \\\"Read overrun during VarInt parsing\\\");\\n require(_index < _nOuts, \\\"Vout read overrun\\\");\\n\\n uint256 _len = 0;\\n uint256 _offset = 1 + _varIntDataLen;\\n\\n for (uint256 _i = 0; _i < _index; _i ++) {\\n _len = determineOutputLengthAt(_vout, _offset);\\n require(_len != ERR_BAD_ARG, \\\"Bad VarInt in scriptPubkey\\\");\\n _offset += _len;\\n }\\n\\n _len = determineOutputLengthAt(_vout, _offset);\\n require(_len != ERR_BAD_ARG, \\\"Bad VarInt in scriptPubkey\\\");\\n return _vout.slice(_offset, _len);\\n }\\n\\n /// @notice Extracts the value bytes from the output in a tx\\n /// @dev Value is an 8-byte little-endian number\\n /// @param _output The output\\n /// @return The output value as LE bytes\\n function extractValueLE(bytes memory _output) internal pure returns (bytes8) {\\n return _output.slice8(0);\\n }\\n\\n /// @notice Extracts the value from the output in a tx\\n /// @dev Value is an 8-byte little-endian number\\n /// @param _output The output\\n /// @return The output value\\n function extractValue(bytes memory _output) internal pure returns (uint64) {\\n uint64 _leValue = uint64(extractValueLE(_output));\\n uint64 _beValue = reverseUint64(_leValue);\\n return _beValue;\\n }\\n\\n /// @notice Extracts the value from the output in a tx\\n /// @dev Value is an 8-byte little-endian number\\n /// @param _output The byte array containing the output\\n /// @param _at The starting index of the output in the array\\n /// @return The output value\\n function extractValueAt(bytes memory _output, uint256 _at) internal pure returns (uint64) {\\n uint64 _leValue = uint64(_output.slice8(_at));\\n uint64 _beValue = reverseUint64(_leValue);\\n return _beValue;\\n }\\n\\n /// @notice Extracts the data from an op return output\\n /// @dev Returns hex\\\"\\\" if no data or not an op return\\n /// @param _output The output\\n /// @return Any data contained in the opreturn output, null if not an op return\\n function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) {\\n if (_output[9] != hex\\\"6a\\\") {\\n return hex\\\"\\\";\\n }\\n bytes1 _dataLen = _output[10];\\n return _output.slice(11, uint256(uint8(_dataLen)));\\n }\\n\\n /// @notice Extracts the hash from the output script\\n /// @dev Determines type by the length prefix and validates format\\n /// @param _output The output\\n /// @return The hash committed to by the pk_script, or null for errors\\n function extractHash(bytes memory _output) internal pure returns (bytes memory) {\\n return extractHashAt(_output, 8, _output.length - 8);\\n }\\n\\n /// @notice Extracts the hash from the output script\\n /// @dev Determines type by the length prefix and validates format\\n /// @param _output The byte array containing the output\\n /// @param _at The starting index of the output script in the array\\n /// (output start + 8)\\n /// @param _len The length of the output script\\n /// (output length - 8)\\n /// @return The hash committed to by the pk_script, or null for errors\\n function extractHashAt(\\n bytes memory _output,\\n uint256 _at,\\n uint256 _len\\n ) internal pure returns (bytes memory) {\\n uint8 _scriptLen = uint8(_output[_at]);\\n\\n // don't have to worry about overflow here.\\n // if _scriptLen + 1 overflows, then output length would have to be < 1\\n // for this check to pass. if it's < 1, then we errored when assigning\\n // _scriptLen\\n if (_scriptLen + 1 != _len) {\\n return hex\\\"\\\";\\n }\\n\\n if (uint8(_output[_at + 1]) == 0) {\\n if (_scriptLen < 2) {\\n return hex\\\"\\\";\\n }\\n uint256 _payloadLen = uint8(_output[_at + 2]);\\n // Check for maliciously formatted witness outputs.\\n // No need to worry about underflow as long b/c of the `< 2` check\\n if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) {\\n return hex\\\"\\\";\\n }\\n return _output.slice(_at + 3, _payloadLen);\\n } else {\\n bytes3 _tag = _output.slice3(_at);\\n // p2pkh\\n if (_tag == hex\\\"1976a9\\\") {\\n // Check for maliciously formatted p2pkh\\n // No need to worry about underflow, b/c of _scriptLen check\\n if (uint8(_output[_at + 3]) != 0x14 ||\\n _output.slice2(_at + _len - 2) != hex\\\"88ac\\\") {\\n return hex\\\"\\\";\\n }\\n return _output.slice(_at + 4, 20);\\n //p2sh\\n } else if (_tag == hex\\\"17a914\\\") {\\n // Check for maliciously formatted p2sh\\n // No need to worry about underflow, b/c of _scriptLen check\\n if (uint8(_output[_at + _len - 1]) != 0x87) {\\n return hex\\\"\\\";\\n }\\n return _output.slice(_at + 3, 20);\\n }\\n }\\n return hex\\\"\\\"; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */\\n }\\n\\n /* ********** */\\n /* Witness TX */\\n /* ********** */\\n\\n\\n /// @notice Checks that the vin passed up is properly formatted\\n /// @dev Consider a vin with a valid vout in its scriptsig\\n /// @param _vin Raw bytes length-prefixed input vector\\n /// @return True if it represents a validly formatted vin\\n function validateVin(bytes memory _vin) internal pure returns (bool) {\\n uint256 _varIntDataLen;\\n uint256 _nIns;\\n\\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\\n\\n // Not valid if it says there are too many or no inputs\\n if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) {\\n return false;\\n }\\n\\n uint256 _offset = 1 + _varIntDataLen;\\n\\n for (uint256 i = 0; i < _nIns; i++) {\\n // If we're at the end, but still expect more\\n if (_offset >= _vin.length) {\\n return false;\\n }\\n\\n // Grab the next input and determine its length.\\n uint256 _nextLen = determineInputLengthAt(_vin, _offset);\\n if (_nextLen == ERR_BAD_ARG) {\\n return false;\\n }\\n\\n // Increase the offset by that much\\n _offset += _nextLen;\\n }\\n\\n // Returns false if we're not exactly at the end\\n return _offset == _vin.length;\\n }\\n\\n /// @notice Checks that the vout passed up is properly formatted\\n /// @dev Consider a vout with a valid scriptpubkey\\n /// @param _vout Raw bytes length-prefixed output vector\\n /// @return True if it represents a validly formatted vout\\n function validateVout(bytes memory _vout) internal pure returns (bool) {\\n uint256 _varIntDataLen;\\n uint256 _nOuts;\\n\\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\\n\\n // Not valid if it says there are too many or no outputs\\n if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) {\\n return false;\\n }\\n\\n uint256 _offset = 1 + _varIntDataLen;\\n\\n for (uint256 i = 0; i < _nOuts; i++) {\\n // If we're at the end, but still expect more\\n if (_offset >= _vout.length) {\\n return false;\\n }\\n\\n // Grab the next output and determine its length.\\n // Increase the offset by that much\\n uint256 _nextLen = determineOutputLengthAt(_vout, _offset);\\n if (_nextLen == ERR_BAD_ARG) {\\n return false;\\n }\\n\\n _offset += _nextLen;\\n }\\n\\n // Returns false if we're not exactly at the end\\n return _offset == _vout.length;\\n }\\n\\n\\n\\n /* ************ */\\n /* Block Header */\\n /* ************ */\\n\\n /// @notice Extracts the transaction merkle root from a block header\\n /// @dev Use verifyHash256Merkle to verify proofs with this root\\n /// @param _header The header\\n /// @return The merkle root (little-endian)\\n function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes32) {\\n return _header.slice32(36);\\n }\\n\\n /// @notice Extracts the target from a block header\\n /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\\n /// @param _header The header\\n /// @return The target threshold\\n function extractTarget(bytes memory _header) internal pure returns (uint256) {\\n return extractTargetAt(_header, 0);\\n }\\n\\n /// @notice Extracts the target from a block header\\n /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\\n /// @param _header The array containing the header\\n /// @param at The start of the header\\n /// @return The target threshold\\n function extractTargetAt(bytes memory _header, uint256 at) internal pure returns (uint256) {\\n uint24 _m = uint24(_header.slice3(72 + at));\\n uint8 _e = uint8(_header[75 + at]);\\n uint256 _mantissa = uint256(reverseUint24(_m));\\n uint _exponent = _e - 3;\\n\\n return _mantissa * (256 ** _exponent);\\n }\\n\\n /// @notice Calculate difficulty from the difficulty 1 target and current target\\n /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet\\n /// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\\n /// @param _target The current target\\n /// @return The block difficulty (bdiff)\\n function calculateDifficulty(uint256 _target) internal pure returns (uint256) {\\n // Difficulty 1 calculated from 0x1d00ffff\\n return DIFF1_TARGET.div(_target);\\n }\\n\\n /// @notice Extracts the previous block's hash from a block header\\n /// @dev Block headers do NOT include block number :(\\n /// @param _header The header\\n /// @return The previous block's hash (little-endian)\\n function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes32) {\\n return _header.slice32(4);\\n }\\n\\n /// @notice Extracts the previous block's hash from a block header\\n /// @dev Block headers do NOT include block number :(\\n /// @param _header The array containing the header\\n /// @param at The start of the header\\n /// @return The previous block's hash (little-endian)\\n function extractPrevBlockLEAt(\\n bytes memory _header,\\n uint256 at\\n ) internal pure returns (bytes32) {\\n return _header.slice32(4 + at);\\n }\\n\\n /// @notice Extracts the timestamp from a block header\\n /// @dev Time is not 100% reliable\\n /// @param _header The header\\n /// @return The timestamp (little-endian bytes)\\n function extractTimestampLE(bytes memory _header) internal pure returns (bytes4) {\\n return _header.slice4(68);\\n }\\n\\n /// @notice Extracts the timestamp from a block header\\n /// @dev Time is not 100% reliable\\n /// @param _header The header\\n /// @return The timestamp (uint)\\n function extractTimestamp(bytes memory _header) internal pure returns (uint32) {\\n return reverseUint32(uint32(extractTimestampLE(_header)));\\n }\\n\\n /// @notice Extracts the expected difficulty from a block header\\n /// @dev Does NOT verify the work\\n /// @param _header The header\\n /// @return The difficulty as an integer\\n function extractDifficulty(bytes memory _header) internal pure returns (uint256) {\\n return calculateDifficulty(extractTarget(_header));\\n }\\n\\n /// @notice Concatenates and hashes two inputs for merkle proving\\n /// @param _a The first hash\\n /// @param _b The second hash\\n /// @return The double-sha256 of the concatenated hashes\\n function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal view returns (bytes32) {\\n return hash256View(abi.encodePacked(_a, _b));\\n }\\n\\n /// @notice Concatenates and hashes two inputs for merkle proving\\n /// @param _a The first hash\\n /// @param _b The second hash\\n /// @return The double-sha256 of the concatenated hashes\\n function _hash256MerkleStep(bytes32 _a, bytes32 _b) internal view returns (bytes32) {\\n return hash256Pair(_a, _b);\\n }\\n\\n\\n /// @notice Verifies a Bitcoin-style merkle tree\\n /// @dev Leaves are 0-indexed. Inefficient version.\\n /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root\\n /// @param _index The index of the leaf\\n /// @return true if the proof is valid, else false\\n function verifyHash256Merkle(bytes memory _proof, uint _index) internal view returns (bool) {\\n // Not an even number of hashes\\n if (_proof.length % 32 != 0) {\\n return false;\\n }\\n\\n // Special case for coinbase-only blocks\\n if (_proof.length == 32) {\\n return true;\\n }\\n\\n // Should never occur\\n if (_proof.length == 64) {\\n return false;\\n }\\n\\n bytes32 _root = _proof.slice32(_proof.length - 32);\\n bytes32 _current = _proof.slice32(0);\\n bytes memory _tree = _proof.slice(32, _proof.length - 64);\\n\\n return verifyHash256Merkle(_current, _tree, _root, _index);\\n }\\n\\n /// @notice Verifies a Bitcoin-style merkle tree\\n /// @dev Leaves are 0-indexed. Efficient version.\\n /// @param _leaf The leaf of the proof. LE sha256 hash.\\n /// @param _tree The intermediate nodes in the proof.\\n /// Tightly packed LE sha256 hashes.\\n /// @param _root The root of the proof. LE sha256 hash.\\n /// @param _index The index of the leaf\\n /// @return true if the proof is valid, else false\\n function verifyHash256Merkle(\\n bytes32 _leaf,\\n bytes memory _tree,\\n bytes32 _root,\\n uint _index\\n ) internal view returns (bool) {\\n // Not an even number of hashes\\n if (_tree.length % 32 != 0) {\\n return false;\\n }\\n\\n // Should never occur\\n if (_tree.length == 0) {\\n return false;\\n }\\n\\n uint _idx = _index;\\n bytes32 _current = _leaf;\\n\\n // i moves in increments of 32\\n for (uint i = 0; i < _tree.length; i += 32) {\\n if (_idx % 2 == 1) {\\n _current = _hash256MerkleStep(_tree.slice32(i), _current);\\n } else {\\n _current = _hash256MerkleStep(_current, _tree.slice32(i));\\n }\\n _idx = _idx >> 1;\\n }\\n return _current == _root;\\n }\\n\\n /*\\n NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72\\n NB: We get a full-bitlength target from this. For comparison with\\n header-encoded targets we need to mask it with the header target\\n e.g. (full & truncated) == truncated\\n */\\n /// @notice performs the bitcoin difficulty retarget\\n /// @dev implements the Bitcoin algorithm precisely\\n /// @param _previousTarget the target of the previous period\\n /// @param _firstTimestamp the timestamp of the first block in the difficulty period\\n /// @param _secondTimestamp the timestamp of the last block in the difficulty period\\n /// @return the new period's target threshold\\n function retargetAlgorithm(\\n uint256 _previousTarget,\\n uint256 _firstTimestamp,\\n uint256 _secondTimestamp\\n ) internal pure returns (uint256) {\\n uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);\\n\\n // Normalize ratio to factor of 4 if very long or very short\\n if (_elapsedTime < RETARGET_PERIOD.div(4)) {\\n _elapsedTime = RETARGET_PERIOD.div(4);\\n }\\n if (_elapsedTime > RETARGET_PERIOD.mul(4)) {\\n _elapsedTime = RETARGET_PERIOD.mul(4);\\n }\\n\\n /*\\n NB: high targets e.g. ffff0020 can cause overflows here\\n so we divide it by 256**2, then multiply by 256**2 later\\n we know the target is evenly divisible by 256**2, so this isn't an issue\\n */\\n\\n uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);\\n return _adjusted.div(RETARGET_PERIOD).mul(65536);\\n }\\n}\\n\",\"keccak256\":\"0x439eaa97e9239705f3d31e8d39dccbad32311f1f119e295d53c65e0ae3c5a5fc\"},\"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\":{\"content\":\"pragma solidity ^0.8.4;\\n\\n/*\\n\\nhttps://github.com/GNSPS/solidity-bytes-utils/\\n\\nThis is free and unencumbered software released into the public domain.\\n\\nAnyone is free to copy, modify, publish, use, compile, sell, or\\ndistribute this software, either in source code form or as a compiled\\nbinary, for any purpose, commercial or non-commercial, and by any\\nmeans.\\n\\nIn jurisdictions that recognize copyright laws, the author or authors\\nof this software dedicate any and all copyright interest in the\\nsoftware to the public domain. We make this dedication for the benefit\\nof the public at large and to the detriment of our heirs and\\nsuccessors. We intend this dedication to be an overt act of\\nrelinquishment in perpetuity of all present and future rights to this\\nsoftware under copyright law.\\n\\nTHE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND,\\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\\nOTHER DEALINGS IN THE SOFTWARE.\\n\\nFor more information, please refer to \\n*/\\n\\n\\n/** @title BytesLib **/\\n/** @author https://github.com/GNSPS **/\\n\\nlibrary BytesLib {\\n function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {\\n bytes memory tempBytes;\\n\\n assembly {\\n // Get a location of some free memory and store it in tempBytes as\\n // Solidity does for memory variables.\\n tempBytes := mload(0x40)\\n\\n // Store the length of the first bytes array at the beginning of\\n // the memory for tempBytes.\\n let length := mload(_preBytes)\\n mstore(tempBytes, length)\\n\\n // Maintain a memory counter for the current write location in the\\n // temp bytes array by adding the 32 bytes for the array length to\\n // the starting location.\\n let mc := add(tempBytes, 0x20)\\n // Stop copying when the memory counter reaches the length of the\\n // first bytes array.\\n let end := add(mc, length)\\n\\n for {\\n // Initialize a copy counter to the start of the _preBytes data,\\n // 32 bytes into its memory.\\n let cc := add(_preBytes, 0x20)\\n } lt(mc, end) {\\n // Increase both counters by 32 bytes each iteration.\\n mc := add(mc, 0x20)\\n cc := add(cc, 0x20)\\n } {\\n // Write the _preBytes data into the tempBytes memory 32 bytes\\n // at a time.\\n mstore(mc, mload(cc))\\n }\\n\\n // Add the length of _postBytes to the current length of tempBytes\\n // and store it as the new length in the first 32 bytes of the\\n // tempBytes memory.\\n length := mload(_postBytes)\\n mstore(tempBytes, add(length, mload(tempBytes)))\\n\\n // Move the memory counter back from a multiple of 0x20 to the\\n // actual end of the _preBytes data.\\n mc := end\\n // Stop copying when the memory counter reaches the new combined\\n // length of the arrays.\\n end := add(mc, length)\\n\\n for {\\n let cc := add(_postBytes, 0x20)\\n } lt(mc, end) {\\n mc := add(mc, 0x20)\\n cc := add(cc, 0x20)\\n } {\\n mstore(mc, mload(cc))\\n }\\n\\n // Update the free-memory pointer by padding our last write location\\n // to 32 bytes: add 31 bytes to the end of tempBytes to move to the\\n // next 32 byte block, then round down to the nearest multiple of\\n // 32. If the sum of the length of the two arrays is zero then add\\n // one before rounding down to leave a blank 32 bytes (the length block with 0).\\n mstore(0x40, and(\\n add(add(end, iszero(add(length, mload(_preBytes)))), 31),\\n not(31) // Round down to the nearest 32 bytes.\\n ))\\n }\\n\\n return tempBytes;\\n }\\n\\n function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {\\n assembly {\\n // Read the first 32 bytes of _preBytes storage, which is the length\\n // of the array. (We don't need to use the offset into the slot\\n // because arrays use the entire slot.)\\n let fslot := sload(_preBytes.slot)\\n // Arrays of 31 bytes or less have an even value in their slot,\\n // while longer arrays have an odd value. The actual length is\\n // the slot divided by two for odd values, and the lowest order\\n // byte divided by two for even values.\\n // If the slot is even, bitwise and the slot with 255 and divide by\\n // two to get the length. If the slot is odd, bitwise and the slot\\n // with -1 and divide by two.\\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\\n let mlength := mload(_postBytes)\\n let newlength := add(slength, mlength)\\n // slength can contain both the length and contents of the array\\n // if length < 32 bytes so let's prepare for that\\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\\n switch add(lt(slength, 32), lt(newlength, 32))\\n case 2 {\\n // Since the new array still fits in the slot, we just need to\\n // update the contents of the slot.\\n // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length\\n sstore(\\n _preBytes.slot,\\n // all the modifications to the slot are inside this\\n // next block\\n add(\\n // we can just add to the slot contents because the\\n // bytes we want to change are the LSBs\\n fslot,\\n add(\\n mul(\\n div(\\n // load the bytes from memory\\n mload(add(_postBytes, 0x20)),\\n // zero all bytes to the right\\n exp(0x100, sub(32, mlength))\\n ),\\n // and now shift left the number of bytes to\\n // leave space for the length in the slot\\n exp(0x100, sub(32, newlength))\\n ),\\n // increase length by the double of the memory\\n // bytes length\\n mul(mlength, 2)\\n )\\n )\\n )\\n }\\n case 1 {\\n // The stored value fits in the slot, but the combined value\\n // will exceed it.\\n // get the keccak hash to get the contents of the array\\n mstore(0x0, _preBytes.slot)\\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\\n\\n // save new length\\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\\n\\n // The contents of the _postBytes array start 32 bytes into\\n // the structure. Our first read should obtain the `submod`\\n // bytes that can fit into the unused space in the last word\\n // of the stored array. To get this, we read 32 bytes starting\\n // from `submod`, so the data we read overlaps with the array\\n // contents by `submod` bytes. Masking the lowest-order\\n // `submod` bytes allows us to add that value directly to the\\n // stored value.\\n\\n let submod := sub(32, slength)\\n let mc := add(_postBytes, submod)\\n let end := add(_postBytes, mlength)\\n let mask := sub(exp(0x100, submod), 1)\\n\\n sstore(\\n sc,\\n add(\\n and(\\n fslot,\\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00\\n ),\\n and(mload(mc), mask)\\n )\\n )\\n\\n for {\\n mc := add(mc, 0x20)\\n sc := add(sc, 1)\\n } lt(mc, end) {\\n sc := add(sc, 1)\\n mc := add(mc, 0x20)\\n } {\\n sstore(sc, mload(mc))\\n }\\n\\n mask := exp(0x100, sub(mc, end))\\n\\n sstore(sc, mul(div(mload(mc), mask), mask))\\n }\\n default {\\n // get the keccak hash to get the contents of the array\\n mstore(0x0, _preBytes.slot)\\n // Start copying to the last used word of the stored array.\\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\\n\\n // save new length\\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\\n\\n // Copy over the first `submod` bytes of the new data as in\\n // case 1 above.\\n let slengthmod := mod(slength, 32)\\n let mlengthmod := mod(mlength, 32)\\n let submod := sub(32, slengthmod)\\n let mc := add(_postBytes, submod)\\n let end := add(_postBytes, mlength)\\n let mask := sub(exp(0x100, submod), 1)\\n\\n sstore(sc, add(sload(sc), and(mload(mc), mask)))\\n\\n for {\\n sc := add(sc, 1)\\n mc := add(mc, 0x20)\\n } lt(mc, end) {\\n sc := add(sc, 1)\\n mc := add(mc, 0x20)\\n } {\\n sstore(sc, mload(mc))\\n }\\n\\n mask := exp(0x100, sub(mc, end))\\n\\n sstore(sc, mul(div(mload(mc), mask), mask))\\n }\\n }\\n }\\n\\n function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) {\\n if (_length == 0) {\\n return hex\\\"\\\";\\n }\\n uint _end = _start + _length;\\n require(_end > _start && _bytes.length >= _end, \\\"Slice out of bounds\\\");\\n\\n assembly {\\n // Alloc bytes array with additional 32 bytes afterspace and assign it's size\\n res := mload(0x40)\\n mstore(0x40, add(add(res, 64), _length))\\n mstore(res, _length)\\n\\n // Compute distance between source and destination pointers\\n let diff := sub(res, add(_bytes, _start))\\n\\n for {\\n let src := add(add(_bytes, 32), _start)\\n let end := add(src, _length)\\n } lt(src, end) {\\n src := add(src, 32)\\n } {\\n mstore(add(src, diff), mload(src))\\n }\\n }\\n }\\n\\n /// @notice Take a slice of the byte array, overwriting the destination.\\n /// The length of the slice will equal the length of the destination array.\\n /// @dev Make sure the destination array has afterspace if required.\\n /// @param _bytes The source array\\n /// @param _dest The destination array.\\n /// @param _start The location to start in the source array.\\n function sliceInPlace(\\n bytes memory _bytes,\\n bytes memory _dest,\\n uint _start\\n ) internal pure {\\n uint _length = _dest.length;\\n uint _end = _start + _length;\\n require(_end > _start && _bytes.length >= _end, \\\"Slice out of bounds\\\");\\n\\n assembly {\\n for {\\n let src := add(add(_bytes, 32), _start)\\n let res := add(_dest, 32)\\n let end := add(src, _length)\\n } lt(src, end) {\\n src := add(src, 32)\\n res := add(res, 32)\\n } {\\n mstore(res, mload(src))\\n }\\n }\\n }\\n\\n // Static slice functions, no bounds checking\\n /// @notice take a 32-byte slice from the specified position\\n function slice32(bytes memory _bytes, uint _start) internal pure returns (bytes32 res) {\\n assembly {\\n res := mload(add(add(_bytes, 32), _start))\\n }\\n }\\n\\n /// @notice take a 20-byte slice from the specified position\\n function slice20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {\\n return bytes20(slice32(_bytes, _start));\\n }\\n\\n /// @notice take a 8-byte slice from the specified position\\n function slice8(bytes memory _bytes, uint _start) internal pure returns (bytes8) {\\n return bytes8(slice32(_bytes, _start));\\n }\\n\\n /// @notice take a 4-byte slice from the specified position\\n function slice4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {\\n return bytes4(slice32(_bytes, _start));\\n }\\n\\n /// @notice take a 3-byte slice from the specified position\\n function slice3(bytes memory _bytes, uint _start) internal pure returns (bytes3) {\\n return bytes3(slice32(_bytes, _start));\\n }\\n\\n /// @notice take a 2-byte slice from the specified position\\n function slice2(bytes memory _bytes, uint _start) internal pure returns (bytes2) {\\n return bytes2(slice32(_bytes, _start));\\n }\\n\\n function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {\\n uint _totalLen = _start + 20;\\n require(_totalLen > _start && _bytes.length >= _totalLen, \\\"Address conversion out of bounds.\\\");\\n address tempAddress;\\n\\n assembly {\\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\\n }\\n\\n return tempAddress;\\n }\\n\\n function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {\\n uint _totalLen = _start + 32;\\n require(_totalLen > _start && _bytes.length >= _totalLen, \\\"Uint conversion out of bounds.\\\");\\n uint256 tempUint;\\n\\n assembly {\\n tempUint := mload(add(add(_bytes, 0x20), _start))\\n }\\n\\n return tempUint;\\n }\\n\\n function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {\\n bool success = true;\\n\\n assembly {\\n let length := mload(_preBytes)\\n\\n // if lengths don't match the arrays are not equal\\n switch eq(length, mload(_postBytes))\\n case 1 {\\n // cb is a circuit breaker in the for loop since there's\\n // no said feature for inline assembly loops\\n // cb = 1 - don't breaker\\n // cb = 0 - break\\n let cb := 1\\n\\n let mc := add(_preBytes, 0x20)\\n let end := add(mc, length)\\n\\n for {\\n let cc := add(_postBytes, 0x20)\\n // the next line is the loop condition:\\n // while(uint(mc < end) + cb == 2)\\n } eq(add(lt(mc, end), cb), 2) {\\n mc := add(mc, 0x20)\\n cc := add(cc, 0x20)\\n } {\\n // if any of these checks fails then arrays are not equal\\n if iszero(eq(mload(mc), mload(cc))) {\\n // unsuccess:\\n success := 0\\n cb := 0\\n }\\n }\\n }\\n default {\\n // unsuccess:\\n success := 0\\n }\\n }\\n\\n return success;\\n }\\n\\n function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {\\n bool success = true;\\n\\n assembly {\\n // we know _preBytes_offset is 0\\n let fslot := sload(_preBytes.slot)\\n // Decode the length of the stored array like in concatStorage().\\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\\n let mlength := mload(_postBytes)\\n\\n // if lengths don't match the arrays are not equal\\n switch eq(slength, mlength)\\n case 1 {\\n // slength can contain both the length and contents of the array\\n // if length < 32 bytes so let's prepare for that\\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\\n if iszero(iszero(slength)) {\\n switch lt(slength, 32)\\n case 1 {\\n // blank the last byte which is the length\\n fslot := mul(div(fslot, 0x100), 0x100)\\n\\n if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {\\n // unsuccess:\\n success := 0\\n }\\n }\\n default {\\n // cb is a circuit breaker in the for loop since there's\\n // no said feature for inline assembly loops\\n // cb = 1 - don't breaker\\n // cb = 0 - break\\n let cb := 1\\n\\n // get the keccak hash to get the contents of the array\\n mstore(0x0, _preBytes.slot)\\n let sc := keccak256(0x0, 0x20)\\n\\n let mc := add(_postBytes, 0x20)\\n let end := add(mc, mlength)\\n\\n // the next line is the loop condition:\\n // while(uint(mc < end) + cb == 2)\\n for {} eq(add(lt(mc, end), cb), 2) {\\n sc := add(sc, 1)\\n mc := add(mc, 0x20)\\n } {\\n if iszero(eq(sload(sc), mload(mc))) {\\n // unsuccess:\\n success := 0\\n cb := 0\\n }\\n }\\n }\\n }\\n }\\n default {\\n // unsuccess:\\n success := 0\\n }\\n }\\n\\n return success;\\n }\\n\\n function toBytes32(bytes memory _source) pure internal returns (bytes32 result) {\\n if (_source.length == 0) {\\n return 0x0;\\n }\\n\\n assembly {\\n result := mload(add(_source, 32))\\n }\\n }\\n\\n function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) {\\n uint _end = _start + _length;\\n require(_end > _start && _bytes.length >= _end, \\\"Slice out of bounds\\\");\\n\\n assembly {\\n result := keccak256(add(add(_bytes, 32), _start), _length)\\n }\\n }\\n}\\n\",\"keccak256\":\"0x43e0f3b3b23c861bd031588bf410dfdd02e2af17941a89aa38d70e534e0380d1\"},\"@keep-network/bitcoin-spv-sol/contracts/SafeMath.sol\":{\"content\":\"pragma solidity ^0.8.4;\\n\\n/*\\nThe MIT License (MIT)\\n\\nCopyright (c) 2016 Smart Contract Solutions, Inc.\\n\\nPermission is hereby granted, free of charge, to any person obtaining\\na copy of this software and associated documentation files (the\\n\\\"Software\\\"), to deal in the Software without restriction, including\\nwithout limitation the rights to use, copy, modify, merge, publish,\\ndistribute, sublicense, and/or sell copies of the Software, and to\\npermit persons to whom the Software is furnished to do so, subject to\\nthe following conditions:\\n\\nThe above copyright notice and this permission notice shall be included\\nin all copies or substantial portions of the Software.\\n\\nTHE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\\n*/\\n\\n\\n/**\\n * @title SafeMath\\n * @dev Math operations with safety checks that throw on error\\n */\\nlibrary SafeMath {\\n\\n /**\\n * @dev Multiplies two numbers, throws on overflow.\\n */\\n function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\\n // Gas optimization: this is cheaper than asserting 'a' not being zero, but the\\n // benefit is lost if 'b' is also tested.\\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\\n if (_a == 0) {\\n return 0;\\n }\\n\\n c = _a * _b;\\n require(c / _a == _b, \\\"Overflow during multiplication.\\\");\\n return c;\\n }\\n\\n /**\\n * @dev Integer division of two numbers, truncating the quotient.\\n */\\n function div(uint256 _a, uint256 _b) internal pure returns (uint256) {\\n // assert(_b > 0); // Solidity automatically throws when dividing by 0\\n // uint256 c = _a / _b;\\n // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold\\n return _a / _b;\\n }\\n\\n /**\\n * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).\\n */\\n function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {\\n require(_b <= _a, \\\"Underflow during subtraction.\\\");\\n return _a - _b;\\n }\\n\\n /**\\n * @dev Adds two numbers, throws on overflow.\\n */\\n function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\\n c = _a + _b;\\n require(c >= _a, \\\"Overflow during addition.\\\");\\n return c;\\n }\\n}\\n\",\"keccak256\":\"0x35930d982394c7ffde439b82e5e696c5b21a6f09699d44861dfe409ef64084a3\"},\"@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\n\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n\\npragma solidity ^0.8.0;\\n\\nimport {BTCUtils} from \\\"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\\\";\\n\\nimport \\\"./IBridge.sol\\\";\\nimport \\\"./ITBTCVault.sol\\\";\\n\\n/// @title Abstract AbstractTBTCDepositor contract.\\n/// @notice This abstract contract is meant to facilitate integration of protocols\\n/// aiming to use tBTC as an underlying Bitcoin bridge.\\n///\\n/// Such an integrator is supposed to:\\n/// - Create a child contract inheriting from this abstract contract\\n/// - Call the `__AbstractTBTCDepositor_initialize` initializer function\\n/// - Use the `_initializeDeposit` and `_finalizeDeposit` as part of their\\n/// business logic in order to initialize and finalize deposits.\\n///\\n/// @dev Example usage:\\n/// ```\\n/// // Example upgradeable integrator contract.\\n/// contract ExampleTBTCIntegrator is AbstractTBTCDepositor, Initializable {\\n/// /// @custom:oz-upgrades-unsafe-allow constructor\\n/// constructor() {\\n/// // Prevents the contract from being initialized again.\\n/// _disableInitializers();\\n/// }\\n///\\n/// function initialize(\\n/// address _bridge,\\n/// address _tbtcVault\\n/// ) external initializer {\\n/// __AbstractTBTCDepositor_initialize(_bridge, _tbtcVault);\\n/// }\\n///\\n/// function startProcess(\\n/// IBridgeTypes.BitcoinTxInfo calldata fundingTx,\\n/// IBridgeTypes.DepositRevealInfo calldata reveal\\n/// ) external {\\n/// // Embed necessary context as extra data.\\n/// bytes32 extraData = ...;\\n///\\n/// uint256 depositKey = _initializeDeposit(\\n/// fundingTx,\\n/// reveal,\\n/// extraData\\n/// );\\n///\\n/// // Use the depositKey to track the process.\\n/// }\\n///\\n/// function finalizeProcess(uint256 depositKey) external {\\n/// // Ensure the function cannot be called for the same deposit\\n/// // twice.\\n///\\n/// (\\n/// uint256 initialDepositAmount,\\n/// uint256 tbtcAmount,\\n/// bytes32 extraData\\n/// ) = _finalizeDeposit(depositKey);\\n///\\n/// // Do something with the minted TBTC using context\\n/// // embedded in the extraData.\\n/// }\\n/// }\\nabstract contract AbstractTBTCDepositor {\\n using BTCUtils for bytes;\\n\\n /// @notice Multiplier to convert satoshi to TBTC token units.\\n uint256 public constant SATOSHI_MULTIPLIER = 10**10;\\n\\n /// @notice Bridge contract address.\\n IBridge public bridge;\\n /// @notice TBTCVault contract address.\\n ITBTCVault public tbtcVault;\\n\\n // Reserved storage space that allows adding more variables without affecting\\n // the storage layout of the child contracts. The convention from OpenZeppelin\\n // suggests the storage space should add up to 50 slots. If more variables are\\n // added in the upcoming versions one need to reduce the array size accordingly.\\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n // slither-disable-next-line unused-state\\n uint256[47] private __gap;\\n\\n event DepositInitialized(uint256 indexed depositKey, uint32 initializedAt);\\n\\n event DepositFinalized(\\n uint256 indexed depositKey,\\n uint256 tbtcAmount,\\n uint32 finalizedAt\\n );\\n\\n /// @notice Initializes the contract. MUST BE CALLED from the child\\n /// contract initializer.\\n // slither-disable-next-line dead-code\\n function __AbstractTBTCDepositor_initialize(\\n address _bridge,\\n address _tbtcVault\\n ) internal {\\n require(\\n address(bridge) == address(0) && address(tbtcVault) == address(0),\\n \\\"AbstractTBTCDepositor already initialized\\\"\\n );\\n\\n require(_bridge != address(0), \\\"Bridge address cannot be zero\\\");\\n require(_tbtcVault != address(0), \\\"TBTCVault address cannot be zero\\\");\\n\\n bridge = IBridge(_bridge);\\n tbtcVault = ITBTCVault(_tbtcVault);\\n }\\n\\n /// @notice Initializes a deposit by revealing it to the Bridge.\\n /// @param fundingTx Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.\\n /// @param reveal Deposit reveal data, see `IBridgeTypes.DepositRevealInfo` struct.\\n /// @param extraData 32-byte deposit extra data.\\n /// @return depositKey Deposit key computed as\\n /// `keccak256(fundingTxHash | reveal.fundingOutputIndex)`. This\\n /// key can be used to refer to the deposit in the Bridge and\\n /// TBTCVault contracts.\\n /// @dev Requirements:\\n /// - The revealed vault address must match the TBTCVault address,\\n /// - All requirements from {Bridge#revealDepositWithExtraData}\\n /// function must be met.\\n /// @dev This function doesn't validate if a deposit has been initialized before,\\n /// as the Bridge won't allow the same deposit to be revealed twice.\\n // slither-disable-next-line dead-code\\n function _initializeDeposit(\\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\\n IBridgeTypes.DepositRevealInfo calldata reveal,\\n bytes32 extraData\\n ) internal returns (uint256) {\\n require(reveal.vault == address(tbtcVault), \\\"Vault address mismatch\\\");\\n\\n uint256 depositKey = _calculateDepositKey(\\n _calculateBitcoinTxHash(fundingTx),\\n reveal.fundingOutputIndex\\n );\\n\\n emit DepositInitialized(\\n depositKey,\\n /* solhint-disable-next-line not-rely-on-time */\\n uint32(block.timestamp)\\n );\\n\\n // The Bridge does not allow to reveal the same deposit twice and\\n // revealed deposits stay there forever. The transaction will revert\\n // if the deposit has already been revealed so, there is no need to do\\n // an explicit check here.\\n bridge.revealDepositWithExtraData(fundingTx, reveal, extraData);\\n\\n return depositKey;\\n }\\n\\n /// @notice Finalizes a deposit by calculating the amount of TBTC minted\\n /// for the deposit.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @return initialDepositAmount Amount of funding transaction deposit. In\\n /// TBTC token decimals precision.\\n /// @return tbtcAmount Approximate amount of TBTC minted for the deposit. In\\n /// TBTC token decimals precision.\\n /// @return extraData 32-byte deposit extra data.\\n /// @dev Requirements:\\n /// - The deposit must be initialized but not finalized\\n /// (in the context of this contract) yet.\\n /// - The deposit must be finalized on the Bridge side. That means the\\n /// deposit must be either swept or optimistically minted.\\n /// @dev THIS FUNCTION DOESN'T VALIDATE IF A DEPOSIT HAS BEEN FINALIZED BEFORE,\\n /// IT IS A RESPONSIBILITY OF THE IMPLEMENTING CONTRACT TO ENSURE THIS\\n /// FUNCTION WON'T BE CALLED TWICE FOR THE SAME DEPOSIT.\\n /// @dev IMPORTANT NOTE: The tbtcAmount returned by this function is an\\n /// approximation. See documentation of the `calculateTbtcAmount`\\n /// responsible for calculating this value for more details.\\n // slither-disable-next-line dead-code\\n function _finalizeDeposit(uint256 depositKey)\\n internal\\n returns (\\n uint256 initialDepositAmount,\\n uint256 tbtcAmount,\\n bytes32 extraData\\n )\\n {\\n IBridgeTypes.DepositRequest memory deposit = bridge.deposits(\\n depositKey\\n );\\n require(deposit.revealedAt != 0, \\\"Deposit not initialized\\\");\\n\\n (, uint64 finalizedAt) = tbtcVault.optimisticMintingRequests(\\n depositKey\\n );\\n\\n require(\\n deposit.sweptAt != 0 || finalizedAt != 0,\\n \\\"Deposit not finalized by the bridge\\\"\\n );\\n\\n initialDepositAmount = deposit.amount * SATOSHI_MULTIPLIER;\\n\\n tbtcAmount = _calculateTbtcAmount(deposit.amount, deposit.treasuryFee);\\n\\n // slither-disable-next-line reentrancy-events\\n emit DepositFinalized(\\n depositKey,\\n tbtcAmount,\\n /* solhint-disable-next-line not-rely-on-time */\\n uint32(block.timestamp)\\n );\\n\\n extraData = deposit.extraData;\\n }\\n\\n /// @notice Calculates the amount of TBTC minted for the deposit.\\n /// @param depositAmountSat Deposit amount in satoshi (1e8 precision).\\n /// This is the actual amount deposited by the deposit creator, i.e.\\n /// the gross amount the Bridge's fees are cut from.\\n /// @param depositTreasuryFeeSat Deposit treasury fee in satoshi (1e8 precision).\\n /// This is an accurate value of the treasury fee that was actually\\n /// cut upon minting.\\n /// @return tbtcAmount Approximate amount of TBTC minted for the deposit.\\n /// @dev IMPORTANT NOTE: The tbtcAmount returned by this function may\\n /// not correspond to the actual amount of TBTC minted for the deposit.\\n /// Although the treasury fee cut upon minting is known precisely,\\n /// this is not the case for the optimistic minting fee and the Bitcoin\\n /// transaction fee. To overcome that problem, this function just takes\\n /// the current maximum allowed values of both fees, at the moment of deposit\\n /// finalization. For the great majority of the deposits, such an\\n /// algorithm will return a tbtcAmount slightly lesser than the\\n /// actual amount of TBTC minted for the deposit. This will cause\\n /// some TBTC to be left in the contract and ensure there is enough\\n /// liquidity to finalize the deposit. However, in some rare cases,\\n /// where the actual values of those fees change between the deposit\\n /// minting and finalization, the tbtcAmount returned by this function\\n /// may be greater than the actual amount of TBTC minted for the deposit.\\n /// If this happens and the reserve coming from previous deposits\\n /// leftovers does not provide enough liquidity, the deposit will have\\n /// to wait for finalization until the reserve is refilled by subsequent\\n /// deposits or a manual top-up. The integrator is responsible for\\n /// handling such cases.\\n // slither-disable-next-line dead-code\\n function _calculateTbtcAmount(\\n uint64 depositAmountSat,\\n uint64 depositTreasuryFeeSat\\n ) internal view virtual returns (uint256) {\\n // Both deposit amount and treasury fee are in the 1e8 satoshi precision.\\n // We need to convert them to the 1e18 TBTC precision.\\n uint256 amountSubTreasury = (depositAmountSat - depositTreasuryFeeSat) *\\n SATOSHI_MULTIPLIER;\\n\\n uint256 omFeeDivisor = tbtcVault.optimisticMintingFeeDivisor();\\n uint256 omFee = omFeeDivisor > 0\\n ? (amountSubTreasury / omFeeDivisor)\\n : 0;\\n\\n // The deposit transaction max fee is in the 1e8 satoshi precision.\\n // We need to convert them to the 1e18 TBTC precision.\\n (, , uint64 depositTxMaxFee, ) = bridge.depositParameters();\\n uint256 txMaxFee = depositTxMaxFee * SATOSHI_MULTIPLIER;\\n\\n return amountSubTreasury - omFee - txMaxFee;\\n }\\n\\n /// @notice Calculates the deposit key for the given funding transaction\\n /// hash and funding output index.\\n /// @param fundingTxHash Funding transaction hash.\\n /// @param fundingOutputIndex Funding output index.\\n /// @return depositKey Deposit key computed as\\n /// `keccak256(fundingTxHash | reveal.fundingOutputIndex)`. This\\n /// key can be used to refer to the deposit in the Bridge and\\n /// TBTCVault contracts.\\n // slither-disable-next-line dead-code\\n function _calculateDepositKey(\\n bytes32 fundingTxHash,\\n uint32 fundingOutputIndex\\n ) internal pure returns (uint256) {\\n return\\n uint256(\\n keccak256(abi.encodePacked(fundingTxHash, fundingOutputIndex))\\n );\\n }\\n\\n /// @notice Calculates the Bitcoin transaction hash for the given Bitcoin\\n /// transaction data.\\n /// @param txInfo Bitcoin transaction data, see `IBridgeTypes.BitcoinTxInfo` struct.\\n /// @return txHash Bitcoin transaction hash.\\n // slither-disable-next-line dead-code\\n function _calculateBitcoinTxHash(IBridgeTypes.BitcoinTxInfo calldata txInfo)\\n internal\\n view\\n returns (bytes32)\\n {\\n return\\n abi\\n .encodePacked(\\n txInfo.version,\\n txInfo.inputVector,\\n txInfo.outputVector,\\n txInfo.locktime\\n )\\n .hash256View();\\n }\\n}\\n\",\"keccak256\":\"0x0cfd2215c106fc17c8166a31839243ad1575806401de60f80d0a4857a2a60078\",\"license\":\"GPL-3.0-only\"},\"@keep-network/tbtc-v2/contracts/integrator/IBridge.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\n\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n\\npragma solidity ^0.8.0;\\n\\n/// @notice Namespace which groups all types relevant to the IBridge interface.\\n/// @dev This is a mirror of the real types used in the Bridge contract.\\n/// This way, the `integrator` subpackage does not need to import\\n/// anything from the `bridge` subpackage and explicitly depend on it.\\n/// This simplifies the dependency graph for integrators.\\nlibrary IBridgeTypes {\\n /// @dev See bridge/BitcoinTx.sol#Info\\n struct BitcoinTxInfo {\\n bytes4 version;\\n bytes inputVector;\\n bytes outputVector;\\n bytes4 locktime;\\n }\\n\\n /// @dev See bridge/Deposit.sol#DepositRevealInfo\\n struct DepositRevealInfo {\\n uint32 fundingOutputIndex;\\n bytes8 blindingFactor;\\n bytes20 walletPubKeyHash;\\n bytes20 refundPubKeyHash;\\n bytes4 refundLocktime;\\n address vault;\\n }\\n\\n /// @dev See bridge/Deposit.sol#DepositRequest\\n struct DepositRequest {\\n address depositor;\\n uint64 amount;\\n uint32 revealedAt;\\n address vault;\\n uint64 treasuryFee;\\n uint32 sweptAt;\\n bytes32 extraData;\\n }\\n}\\n\\n/// @notice Interface of the Bridge contract.\\n/// @dev See bridge/Bridge.sol\\ninterface IBridge {\\n /// @dev See {Bridge#revealDepositWithExtraData}\\n function revealDepositWithExtraData(\\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\\n IBridgeTypes.DepositRevealInfo calldata reveal,\\n bytes32 extraData\\n ) external;\\n\\n /// @dev See {Bridge#deposits}\\n function deposits(uint256 depositKey)\\n external\\n view\\n returns (IBridgeTypes.DepositRequest memory);\\n\\n /// @dev See {Bridge#depositParameters}\\n function depositParameters()\\n external\\n view\\n returns (\\n uint64 depositDustThreshold,\\n uint64 depositTreasuryFeeDivisor,\\n uint64 depositTxMaxFee,\\n uint32 depositRevealAheadPeriod\\n );\\n}\\n\",\"keccak256\":\"0x4e598d96404a19609f511f10503e80f457602ad694d081df739571f67f6e0c4e\",\"license\":\"GPL-3.0-only\"},\"@keep-network/tbtc-v2/contracts/integrator/ITBTCVault.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\n\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n// \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c \\u2590\\u2588\\u2588\\u2588\\u2588\\u258c\\n\\npragma solidity ^0.8.0;\\n\\n/// @notice Interface of the TBTCVault contract.\\n/// @dev See vault/TBTCVault.sol\\ninterface ITBTCVault {\\n /// @dev See {TBTCVault#optimisticMintingRequests}\\n function optimisticMintingRequests(uint256 depositKey)\\n external\\n returns (uint64 requestedAt, uint64 finalizedAt);\\n\\n /// @dev See {TBTCVault#optimisticMintingFeeDivisor}\\n function optimisticMintingFeeDivisor() external view returns (uint32);\\n}\\n\",\"keccak256\":\"0xf259d64c1040e2cbc3d17653491e45c5c3da17f575dac1c175c63c8a5308908e\",\"license\":\"GPL-3.0-only\"},\"@openzeppelin/contracts/access/Ownable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {Context} from \\\"../utils/Context.sol\\\";\\n\\n/**\\n * @dev Contract module which provides a basic access control mechanism, where\\n * there is an account (an owner) that can be granted exclusive access to\\n * specific functions.\\n *\\n * The initial owner is set to the address provided by the deployer. This can\\n * later be changed with {transferOwnership}.\\n *\\n * This module is used through inheritance. It will make available the modifier\\n * `onlyOwner`, which can be applied to your functions to restrict their use to\\n * the owner.\\n */\\nabstract contract Ownable is Context {\\n address private _owner;\\n\\n /**\\n * @dev The caller account is not authorized to perform an operation.\\n */\\n error OwnableUnauthorizedAccount(address account);\\n\\n /**\\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\\n */\\n error OwnableInvalidOwner(address owner);\\n\\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\\n\\n /**\\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\\n */\\n constructor(address initialOwner) {\\n if (initialOwner == address(0)) {\\n revert OwnableInvalidOwner(address(0));\\n }\\n _transferOwnership(initialOwner);\\n }\\n\\n /**\\n * @dev Throws if called by any account other than the owner.\\n */\\n modifier onlyOwner() {\\n _checkOwner();\\n _;\\n }\\n\\n /**\\n * @dev Returns the address of the current owner.\\n */\\n function owner() public view virtual returns (address) {\\n return _owner;\\n }\\n\\n /**\\n * @dev Throws if the sender is not the owner.\\n */\\n function _checkOwner() internal view virtual {\\n if (owner() != _msgSender()) {\\n revert OwnableUnauthorizedAccount(_msgSender());\\n }\\n }\\n\\n /**\\n * @dev Leaves the contract without owner. It will not be possible to call\\n * `onlyOwner` functions. Can only be called by the current owner.\\n *\\n * NOTE: Renouncing ownership will leave the contract without an owner,\\n * thereby disabling any functionality that is only available to the owner.\\n */\\n function renounceOwnership() public virtual onlyOwner {\\n _transferOwnership(address(0));\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Can only be called by the current owner.\\n */\\n function transferOwnership(address newOwner) public virtual onlyOwner {\\n if (newOwner == address(0)) {\\n revert OwnableInvalidOwner(address(0));\\n }\\n _transferOwnership(newOwner);\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Internal function without access restriction.\\n */\\n function _transferOwnership(address newOwner) internal virtual {\\n address oldOwner = _owner;\\n _owner = newOwner;\\n emit OwnershipTransferred(oldOwner, newOwner);\\n }\\n}\\n\",\"keccak256\":\"0xff6d0bb2e285473e5311d9d3caacb525ae3538a80758c10649a4d61029b017bb\",\"license\":\"MIT\"},\"@openzeppelin/contracts/access/Ownable2Step.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {Ownable} from \\\"./Ownable.sol\\\";\\n\\n/**\\n * @dev Contract module which provides access control mechanism, where\\n * there is an account (an owner) that can be granted exclusive access to\\n * specific functions.\\n *\\n * The initial owner is specified at deployment time in the constructor for `Ownable`. This\\n * can later be changed with {transferOwnership} and {acceptOwnership}.\\n *\\n * This module is used through inheritance. It will make available all functions\\n * from parent (Ownable).\\n */\\nabstract contract Ownable2Step is Ownable {\\n address private _pendingOwner;\\n\\n event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\\n\\n /**\\n * @dev Returns the address of the pending owner.\\n */\\n function pendingOwner() public view virtual returns (address) {\\n return _pendingOwner;\\n }\\n\\n /**\\n * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\\n * Can only be called by the current owner.\\n */\\n function transferOwnership(address newOwner) public virtual override onlyOwner {\\n _pendingOwner = newOwner;\\n emit OwnershipTransferStarted(owner(), newOwner);\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\\n * Internal function without access restriction.\\n */\\n function _transferOwnership(address newOwner) internal virtual override {\\n delete _pendingOwner;\\n super._transferOwnership(newOwner);\\n }\\n\\n /**\\n * @dev The new owner accepts the ownership transfer.\\n */\\n function acceptOwnership() public virtual {\\n address sender = _msgSender();\\n if (pendingOwner() != sender) {\\n revert OwnableUnauthorizedAccount(sender);\\n }\\n _transferOwnership(sender);\\n }\\n}\\n\",\"keccak256\":\"0x5d3e5de9eadfa1f8a892eb2e95bbebd3e4b8c8ada5b76f104d383fea518fa688\",\"license\":\"MIT\"},\"@openzeppelin/contracts/interfaces/IERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../token/ERC20/IERC20.sol\\\";\\nimport {IERC20Metadata} from \\\"../token/ERC20/extensions/IERC20Metadata.sol\\\";\\n\\n/**\\n * @dev Interface of the ERC4626 \\\"Tokenized Vault Standard\\\", as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\\n */\\ninterface IERC4626 is IERC20, IERC20Metadata {\\n event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\\n\\n event Withdraw(\\n address indexed sender,\\n address indexed receiver,\\n address indexed owner,\\n uint256 assets,\\n uint256 shares\\n );\\n\\n /**\\n * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\\n *\\n * - MUST be an ERC-20 token contract.\\n * - MUST NOT revert.\\n */\\n function asset() external view returns (address assetTokenAddress);\\n\\n /**\\n * @dev Returns the total amount of the underlying asset that is \\u201cmanaged\\u201d by Vault.\\n *\\n * - SHOULD include any compounding that occurs from yield.\\n * - MUST be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT revert.\\n */\\n function totalAssets() external view returns (uint256 totalManagedAssets);\\n\\n /**\\n * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToShares(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\\n * through a deposit call.\\n *\\n * - MUST return a limited value if receiver is subject to some deposit limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\\n * - MUST NOT revert.\\n */\\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\\n * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\\n * in the same transaction.\\n * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\\n * deposit would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * deposit execution, and are accounted for during deposit.\\n * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\\n * - MUST return a limited value if receiver is subject to some mint limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\\n * - MUST NOT revert.\\n */\\n function maxMint(address receiver) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\\n * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\\n * same transaction.\\n * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\\n * would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by minting.\\n */\\n function previewMint(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\\n * execution, and are accounted for during mint.\\n * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\\n * Vault, through a withdraw call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\\n * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\\n * called\\n * in the same transaction.\\n * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\\n * the withdrawal would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * withdraw execution, and are accounted for during withdraw.\\n * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\\n * through a redeem call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxRedeem(address owner) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\\n * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\\n * same transaction.\\n * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\\n * redemption would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\\n */\\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * redeem execution, and are accounted for during redeem.\\n * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\\n}\\n\",\"keccak256\":\"0x207f64371bc0fcc5be86713aa5da109a870cc3a6da50e93b64ee881e369b593d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Standard ERC20 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.\\n */\\ninterface IERC20Errors {\\n /**\\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param balance Current balance for the interacting account.\\n * @param needed Minimum amount required to perform a transfer.\\n */\\n error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC20InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC20InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `spender`\\u2019s `allowance`. Used in transfers.\\n * @param spender Address that may be allowed to operate on tokens without being their owner.\\n * @param allowance Amount of tokens a `spender` is allowed to operate with.\\n * @param needed Minimum amount required to perform a transfer.\\n */\\n error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC20InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\\n * @param spender Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC20InvalidSpender(address spender);\\n}\\n\\n/**\\n * @dev Standard ERC721 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.\\n */\\ninterface IERC721Errors {\\n /**\\n * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.\\n * Used in balance queries.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC721InvalidOwner(address owner);\\n\\n /**\\n * @dev Indicates a `tokenId` whose `owner` is the zero address.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC721NonexistentToken(uint256 tokenId);\\n\\n /**\\n * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param tokenId Identifier number of a token.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC721InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC721InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `operator`\\u2019s approval. Used in transfers.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC721InsufficientApproval(address operator, uint256 tokenId);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC721InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC721InvalidOperator(address operator);\\n}\\n\\n/**\\n * @dev Standard ERC1155 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.\\n */\\ninterface IERC1155Errors {\\n /**\\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param balance Current balance for the interacting account.\\n * @param needed Minimum amount required to perform a transfer.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC1155InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC1155InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `operator`\\u2019s approval. Used in transfers.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC1155MissingApprovalForAll(address operator, address owner);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC1155InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC1155InvalidOperator(address operator);\\n\\n /**\\n * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\\n * Used in batch transfers.\\n * @param idsLength Length of the array of token identifiers\\n * @param valuesLength Length of the array of token amounts\\n */\\n error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\\n}\\n\",\"keccak256\":\"0x60c65f701957fdd6faea1acb0bb45825791d473693ed9ecb34726fdfaa849dd7\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/ERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"./IERC20.sol\\\";\\nimport {IERC20Metadata} from \\\"./extensions/IERC20Metadata.sol\\\";\\nimport {Context} from \\\"../../utils/Context.sol\\\";\\nimport {IERC20Errors} from \\\"../../interfaces/draft-IERC6093.sol\\\";\\n\\n/**\\n * @dev Implementation of the {IERC20} interface.\\n *\\n * This implementation is agnostic to the way tokens are created. This means\\n * that a supply mechanism has to be added in a derived contract using {_mint}.\\n *\\n * TIP: For a detailed writeup see our guide\\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\\n * to implement supply mechanisms].\\n *\\n * The default value of {decimals} is 18. To change this, you should override\\n * this function so it returns a different value.\\n *\\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\\n * instead returning `false` on failure. This behavior is nonetheless\\n * conventional and does not conflict with the expectations of ERC20\\n * applications.\\n *\\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\\n * This allows applications to reconstruct the allowance for all accounts just\\n * by listening to said events. Other implementations of the EIP may not emit\\n * these events, as it isn't required by the specification.\\n */\\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\\n mapping(address account => uint256) private _balances;\\n\\n mapping(address account => mapping(address spender => uint256)) private _allowances;\\n\\n uint256 private _totalSupply;\\n\\n string private _name;\\n string private _symbol;\\n\\n /**\\n * @dev Sets the values for {name} and {symbol}.\\n *\\n * All two of these values are immutable: they can only be set once during\\n * construction.\\n */\\n constructor(string memory name_, string memory symbol_) {\\n _name = name_;\\n _symbol = symbol_;\\n }\\n\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() public view virtual returns (string memory) {\\n return _name;\\n }\\n\\n /**\\n * @dev Returns the symbol of the token, usually a shorter version of the\\n * name.\\n */\\n function symbol() public view virtual returns (string memory) {\\n return _symbol;\\n }\\n\\n /**\\n * @dev Returns the number of decimals used to get its user representation.\\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\\n *\\n * Tokens usually opt for a value of 18, imitating the relationship between\\n * Ether and Wei. This is the default value returned by this function, unless\\n * it's overridden.\\n *\\n * NOTE: This information is only used for _display_ purposes: it in\\n * no way affects any of the arithmetic of the contract, including\\n * {IERC20-balanceOf} and {IERC20-transfer}.\\n */\\n function decimals() public view virtual returns (uint8) {\\n return 18;\\n }\\n\\n /**\\n * @dev See {IERC20-totalSupply}.\\n */\\n function totalSupply() public view virtual returns (uint256) {\\n return _totalSupply;\\n }\\n\\n /**\\n * @dev See {IERC20-balanceOf}.\\n */\\n function balanceOf(address account) public view virtual returns (uint256) {\\n return _balances[account];\\n }\\n\\n /**\\n * @dev See {IERC20-transfer}.\\n *\\n * Requirements:\\n *\\n * - `to` cannot be the zero address.\\n * - the caller must have a balance of at least `value`.\\n */\\n function transfer(address to, uint256 value) public virtual returns (bool) {\\n address owner = _msgSender();\\n _transfer(owner, to, value);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-allowance}.\\n */\\n function allowance(address owner, address spender) public view virtual returns (uint256) {\\n return _allowances[owner][spender];\\n }\\n\\n /**\\n * @dev See {IERC20-approve}.\\n *\\n * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\\n * `transferFrom`. This is semantically equivalent to an infinite approval.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n */\\n function approve(address spender, uint256 value) public virtual returns (bool) {\\n address owner = _msgSender();\\n _approve(owner, spender, value);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-transferFrom}.\\n *\\n * Emits an {Approval} event indicating the updated allowance. This is not\\n * required by the EIP. See the note at the beginning of {ERC20}.\\n *\\n * NOTE: Does not update the allowance if the current allowance\\n * is the maximum `uint256`.\\n *\\n * Requirements:\\n *\\n * - `from` and `to` cannot be the zero address.\\n * - `from` must have a balance of at least `value`.\\n * - the caller must have allowance for ``from``'s tokens of at least\\n * `value`.\\n */\\n function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\\n address spender = _msgSender();\\n _spendAllowance(from, spender, value);\\n _transfer(from, to, value);\\n return true;\\n }\\n\\n /**\\n * @dev Moves a `value` amount of tokens from `from` to `to`.\\n *\\n * This internal function is equivalent to {transfer}, and can be used to\\n * e.g. implement automatic token fees, slashing mechanisms, etc.\\n *\\n * Emits a {Transfer} event.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead.\\n */\\n function _transfer(address from, address to, uint256 value) internal {\\n if (from == address(0)) {\\n revert ERC20InvalidSender(address(0));\\n }\\n if (to == address(0)) {\\n revert ERC20InvalidReceiver(address(0));\\n }\\n _update(from, to, value);\\n }\\n\\n /**\\n * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\\n * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\\n * this function.\\n *\\n * Emits a {Transfer} event.\\n */\\n function _update(address from, address to, uint256 value) internal virtual {\\n if (from == address(0)) {\\n // Overflow check required: The rest of the code assumes that totalSupply never overflows\\n _totalSupply += value;\\n } else {\\n uint256 fromBalance = _balances[from];\\n if (fromBalance < value) {\\n revert ERC20InsufficientBalance(from, fromBalance, value);\\n }\\n unchecked {\\n // Overflow not possible: value <= fromBalance <= totalSupply.\\n _balances[from] = fromBalance - value;\\n }\\n }\\n\\n if (to == address(0)) {\\n unchecked {\\n // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\\n _totalSupply -= value;\\n }\\n } else {\\n unchecked {\\n // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\\n _balances[to] += value;\\n }\\n }\\n\\n emit Transfer(from, to, value);\\n }\\n\\n /**\\n * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\\n * Relies on the `_update` mechanism\\n *\\n * Emits a {Transfer} event with `from` set to the zero address.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead.\\n */\\n function _mint(address account, uint256 value) internal {\\n if (account == address(0)) {\\n revert ERC20InvalidReceiver(address(0));\\n }\\n _update(address(0), account, value);\\n }\\n\\n /**\\n * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\\n * Relies on the `_update` mechanism.\\n *\\n * Emits a {Transfer} event with `to` set to the zero address.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead\\n */\\n function _burn(address account, uint256 value) internal {\\n if (account == address(0)) {\\n revert ERC20InvalidSender(address(0));\\n }\\n _update(account, address(0), value);\\n }\\n\\n /**\\n * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\\n *\\n * This internal function is equivalent to `approve`, and can be used to\\n * e.g. set automatic allowances for certain subsystems, etc.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `owner` cannot be the zero address.\\n * - `spender` cannot be the zero address.\\n *\\n * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\\n */\\n function _approve(address owner, address spender, uint256 value) internal {\\n _approve(owner, spender, value, true);\\n }\\n\\n /**\\n * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\\n *\\n * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\\n * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\\n * `Approval` event during `transferFrom` operations.\\n *\\n * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\\n * true using the following override:\\n * ```\\n * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\\n * super._approve(owner, spender, value, true);\\n * }\\n * ```\\n *\\n * Requirements are the same as {_approve}.\\n */\\n function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\\n if (owner == address(0)) {\\n revert ERC20InvalidApprover(address(0));\\n }\\n if (spender == address(0)) {\\n revert ERC20InvalidSpender(address(0));\\n }\\n _allowances[owner][spender] = value;\\n if (emitEvent) {\\n emit Approval(owner, spender, value);\\n }\\n }\\n\\n /**\\n * @dev Updates `owner` s allowance for `spender` based on spent `value`.\\n *\\n * Does not update the allowance value in case of infinite allowance.\\n * Revert if not enough allowance is available.\\n *\\n * Does not emit an {Approval} event.\\n */\\n function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\\n uint256 currentAllowance = allowance(owner, spender);\\n if (currentAllowance != type(uint256).max) {\\n if (currentAllowance < value) {\\n revert ERC20InsufficientAllowance(spender, currentAllowance, value);\\n }\\n unchecked {\\n _approve(owner, spender, currentAllowance - value, false);\\n }\\n }\\n }\\n}\\n\",\"keccak256\":\"0xc3e1fa9d1987f8d349dfb4d6fe93bf2ca014b52ba335cfac30bfe71e357e6f80\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/IERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Interface of the ERC20 standard as defined in the EIP.\\n */\\ninterface IERC20 {\\n /**\\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\\n * another (`to`).\\n *\\n * Note that `value` may be zero.\\n */\\n event Transfer(address indexed from, address indexed to, uint256 value);\\n\\n /**\\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\\n * a call to {approve}. `value` is the new allowance.\\n */\\n event Approval(address indexed owner, address indexed spender, uint256 value);\\n\\n /**\\n * @dev Returns the value of tokens in existence.\\n */\\n function totalSupply() external view returns (uint256);\\n\\n /**\\n * @dev Returns the value of tokens owned by `account`.\\n */\\n function balanceOf(address account) external view returns (uint256);\\n\\n /**\\n * @dev Moves a `value` amount of tokens from the caller's account to `to`.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transfer(address to, uint256 value) external returns (bool);\\n\\n /**\\n * @dev Returns the remaining number of tokens that `spender` will be\\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\\n * zero by default.\\n *\\n * This value changes when {approve} or {transferFrom} are called.\\n */\\n function allowance(address owner, address spender) external view returns (uint256);\\n\\n /**\\n * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\\n * caller's tokens.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\\n * that someone may use both the old and the new allowance by unfortunate\\n * transaction ordering. One possible solution to mitigate this race\\n * condition is to first reduce the spender's allowance to 0 and set the\\n * desired value afterwards:\\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\\n *\\n * Emits an {Approval} event.\\n */\\n function approve(address spender, uint256 value) external returns (bool);\\n\\n /**\\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\\n * allowance mechanism. `value` is then deducted from the caller's\\n * allowance.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transferFrom(address from, address to, uint256 value) external returns (bool);\\n}\\n\",\"keccak256\":\"0xc6a8ff0ea489379b61faa647490411b80102578440ab9d84e9a957cc12164e70\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20, IERC20Metadata, ERC20} from \\\"../ERC20.sol\\\";\\nimport {SafeERC20} from \\\"../utils/SafeERC20.sol\\\";\\nimport {IERC4626} from \\\"../../../interfaces/IERC4626.sol\\\";\\nimport {Math} from \\\"../../../utils/math/Math.sol\\\";\\n\\n/**\\n * @dev Implementation of the ERC4626 \\\"Tokenized Vault Standard\\\" as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].\\n *\\n * This extension allows the minting and burning of \\\"shares\\\" (represented using the ERC20 inheritance) in exchange for\\n * underlying \\\"assets\\\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\\n * the ERC20 standard. Any additional extensions included along it would affect the \\\"shares\\\" token represented by this\\n * contract and not the \\\"assets\\\" token which is an independent contract.\\n *\\n * [CAUTION]\\n * ====\\n * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning\\n * with a \\\"donation\\\" to the vault that inflates the price of a share. This is variously known as a donation or inflation\\n * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial\\n * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may\\n * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by\\n * verifying the amount received is as expected, using a wrapper that performs these checks such as\\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\\n *\\n * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`\\n * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault\\n * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself\\n * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset\\n * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's\\n * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more\\n * expensive than it is profitable. More details about the underlying math can be found\\n * xref:erc4626.adoc#inflation-attack[here].\\n *\\n * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued\\n * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets\\n * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience\\n * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the\\n * `_convertToShares` and `_convertToAssets` functions.\\n *\\n * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].\\n * ====\\n */\\nabstract contract ERC4626 is ERC20, IERC4626 {\\n using Math for uint256;\\n\\n IERC20 private immutable _asset;\\n uint8 private immutable _underlyingDecimals;\\n\\n /**\\n * @dev Attempted to deposit more assets than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);\\n\\n /**\\n * @dev Attempted to mint more shares than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);\\n\\n /**\\n * @dev Attempted to withdraw more assets than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);\\n\\n /**\\n * @dev Attempted to redeem more shares than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);\\n\\n /**\\n * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).\\n */\\n constructor(IERC20 asset_) {\\n (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\\n _underlyingDecimals = success ? assetDecimals : 18;\\n _asset = asset_;\\n }\\n\\n /**\\n * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\\n */\\n function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {\\n (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(\\n abi.encodeCall(IERC20Metadata.decimals, ())\\n );\\n if (success && encodedDecimals.length >= 32) {\\n uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));\\n if (returnedDecimals <= type(uint8).max) {\\n return (true, uint8(returnedDecimals));\\n }\\n }\\n return (false, 0);\\n }\\n\\n /**\\n * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This\\n * \\\"original\\\" value is cached during construction of the vault contract. If this read operation fails (e.g., the\\n * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.\\n *\\n * See {IERC20Metadata-decimals}.\\n */\\n function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {\\n return _underlyingDecimals + _decimalsOffset();\\n }\\n\\n /** @dev See {IERC4626-asset}. */\\n function asset() public view virtual returns (address) {\\n return address(_asset);\\n }\\n\\n /** @dev See {IERC4626-totalAssets}. */\\n function totalAssets() public view virtual returns (uint256) {\\n return _asset.balanceOf(address(this));\\n }\\n\\n /** @dev See {IERC4626-convertToShares}. */\\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-convertToAssets}. */\\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-maxDeposit}. */\\n function maxDeposit(address) public view virtual returns (uint256) {\\n return type(uint256).max;\\n }\\n\\n /** @dev See {IERC4626-maxMint}. */\\n function maxMint(address) public view virtual returns (uint256) {\\n return type(uint256).max;\\n }\\n\\n /** @dev See {IERC4626-maxWithdraw}. */\\n function maxWithdraw(address owner) public view virtual returns (uint256) {\\n return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-maxRedeem}. */\\n function maxRedeem(address owner) public view virtual returns (uint256) {\\n return balanceOf(owner);\\n }\\n\\n /** @dev See {IERC4626-previewDeposit}. */\\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-previewMint}. */\\n function previewMint(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Ceil);\\n }\\n\\n /** @dev See {IERC4626-previewWithdraw}. */\\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Ceil);\\n }\\n\\n /** @dev See {IERC4626-previewRedeem}. */\\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-deposit}. */\\n function deposit(uint256 assets, address receiver) public virtual returns (uint256) {\\n uint256 maxAssets = maxDeposit(receiver);\\n if (assets > maxAssets) {\\n revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);\\n }\\n\\n uint256 shares = previewDeposit(assets);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-mint}.\\n *\\n * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.\\n * In this case, the shares will be minted without requiring any assets to be deposited.\\n */\\n function mint(uint256 shares, address receiver) public virtual returns (uint256) {\\n uint256 maxShares = maxMint(receiver);\\n if (shares > maxShares) {\\n revert ERC4626ExceededMaxMint(receiver, shares, maxShares);\\n }\\n\\n uint256 assets = previewMint(shares);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return assets;\\n }\\n\\n /** @dev See {IERC4626-withdraw}. */\\n function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {\\n uint256 maxAssets = maxWithdraw(owner);\\n if (assets > maxAssets) {\\n revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);\\n }\\n\\n uint256 shares = previewWithdraw(assets);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-redeem}. */\\n function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {\\n uint256 maxShares = maxRedeem(owner);\\n if (shares > maxShares) {\\n revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);\\n }\\n\\n uint256 assets = previewRedeem(shares);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return assets;\\n }\\n\\n /**\\n * @dev Internal conversion function (from assets to shares) with support for rounding direction.\\n */\\n function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {\\n return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);\\n }\\n\\n /**\\n * @dev Internal conversion function (from shares to assets) with support for rounding direction.\\n */\\n function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {\\n return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);\\n }\\n\\n /**\\n * @dev Deposit/mint common workflow.\\n */\\n function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {\\n // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the\\n // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\\n // assets are transferred and before the shares are minted, which is a valid state.\\n // slither-disable-next-line reentrancy-no-eth\\n SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);\\n _mint(receiver, shares);\\n\\n emit Deposit(caller, receiver, assets, shares);\\n }\\n\\n /**\\n * @dev Withdraw/redeem common workflow.\\n */\\n function _withdraw(\\n address caller,\\n address receiver,\\n address owner,\\n uint256 assets,\\n uint256 shares\\n ) internal virtual {\\n if (caller != owner) {\\n _spendAllowance(owner, caller, shares);\\n }\\n\\n // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\\n // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\\n // shares are burned and after the assets are transferred, which is a valid state.\\n _burn(owner, shares);\\n SafeERC20.safeTransfer(_asset, receiver, assets);\\n\\n emit Withdraw(caller, receiver, owner, assets, shares);\\n }\\n\\n function _decimalsOffset() internal view virtual returns (uint8) {\\n return 0;\\n }\\n}\\n\",\"keccak256\":\"0x1837547e04d5fe5334eeb77a345683c22995f1e7aa033020757ddf83a80fc72d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../IERC20.sol\\\";\\n\\n/**\\n * @dev Interface for the optional metadata functions from the ERC20 standard.\\n */\\ninterface IERC20Metadata is IERC20 {\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() external view returns (string memory);\\n\\n /**\\n * @dev Returns the symbol of the token.\\n */\\n function symbol() external view returns (string memory);\\n\\n /**\\n * @dev Returns the decimals places of the token.\\n */\\n function decimals() external view returns (uint8);\\n}\\n\",\"keccak256\":\"0xaa761817f6cd7892fcf158b3c776b34551cde36f48ff9703d53898bc45a94ea2\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\\n *\\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\\n * need to send a transaction, and thus is not required to hold Ether at all.\\n *\\n * ==== Security Considerations\\n *\\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\\n * generally recommended is:\\n *\\n * ```solidity\\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\\n * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\\n * doThing(..., value);\\n * }\\n *\\n * function doThing(..., uint256 value) public {\\n * token.safeTransferFrom(msg.sender, address(this), value);\\n * ...\\n * }\\n * ```\\n *\\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\\n * {SafeERC20-safeTransferFrom}).\\n *\\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\\n * contracts should have entry points that don't rely on permit.\\n */\\ninterface IERC20Permit {\\n /**\\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\\n * given ``owner``'s signed approval.\\n *\\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\\n * ordering also apply here.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n * - `deadline` must be a timestamp in the future.\\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\\n * over the EIP712-formatted function arguments.\\n * - the signature must use ``owner``'s current nonce (see {nonces}).\\n *\\n * For more information on the signature format, see the\\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\\n * section].\\n *\\n * CAUTION: See Security Considerations above.\\n */\\n function permit(\\n address owner,\\n address spender,\\n uint256 value,\\n uint256 deadline,\\n uint8 v,\\n bytes32 r,\\n bytes32 s\\n ) external;\\n\\n /**\\n * @dev Returns the current nonce for `owner`. This value must be\\n * included whenever a signature is generated for {permit}.\\n *\\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\\n * prevents a signature from being used multiple times.\\n */\\n function nonces(address owner) external view returns (uint256);\\n\\n /**\\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\\n */\\n // solhint-disable-next-line func-name-mixedcase\\n function DOMAIN_SEPARATOR() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0x6008dabfe393240d73d7dd7688033f72740d570aa422254d29a7dce8568f3aff\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../IERC20.sol\\\";\\nimport {IERC20Permit} from \\\"../extensions/IERC20Permit.sol\\\";\\nimport {Address} from \\\"../../../utils/Address.sol\\\";\\n\\n/**\\n * @title SafeERC20\\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\\n * contract returns false). Tokens that return no value (and instead revert or\\n * throw on failure) are also supported, non-reverting calls are assumed to be\\n * successful.\\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\\n */\\nlibrary SafeERC20 {\\n using Address for address;\\n\\n /**\\n * @dev An operation with an ERC20 token failed.\\n */\\n error SafeERC20FailedOperation(address token);\\n\\n /**\\n * @dev Indicates a failed `decreaseAllowance` request.\\n */\\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\\n\\n /**\\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful.\\n */\\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\\n }\\n\\n /**\\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\\n */\\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\\n }\\n\\n /**\\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful.\\n */\\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\\n uint256 oldAllowance = token.allowance(address(this), spender);\\n forceApprove(token, spender, oldAllowance + value);\\n }\\n\\n /**\\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\\n * value, non-reverting calls are assumed to be successful.\\n */\\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\\n unchecked {\\n uint256 currentAllowance = token.allowance(address(this), spender);\\n if (currentAllowance < requestedDecrease) {\\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\\n }\\n forceApprove(token, spender, currentAllowance - requestedDecrease);\\n }\\n }\\n\\n /**\\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\\n * to be set to zero before setting it to a non-zero value, such as USDT.\\n */\\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\\n\\n if (!_callOptionalReturnBool(token, approvalCall)) {\\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\\n _callOptionalReturn(token, approvalCall);\\n }\\n }\\n\\n /**\\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\\n * on the return value: the return value is optional (but if data is returned, it must not be false).\\n * @param token The token targeted by the call.\\n * @param data The call data (encoded using abi.encode or one of its variants).\\n */\\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\\n // the target address contains contract code and also asserts for success in the low-level call.\\n\\n bytes memory returndata = address(token).functionCall(data);\\n if (returndata.length != 0 && !abi.decode(returndata, (bool))) {\\n revert SafeERC20FailedOperation(address(token));\\n }\\n }\\n\\n /**\\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\\n * on the return value: the return value is optional (but if data is returned, it must not be false).\\n * @param token The token targeted by the call.\\n * @param data The call data (encoded using abi.encode or one of its variants).\\n *\\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\\n */\\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\\n // and not revert is the subcall reverts.\\n\\n (bool success, bytes memory returndata) = address(token).call(data);\\n return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;\\n }\\n}\\n\",\"keccak256\":\"0x37bb49513c49c87c4642a891b13b63571bc87013dde806617aa1efb54605f386\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Address.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary Address {\\n /**\\n * @dev The ETH balance of the account is not enough to perform the operation.\\n */\\n error AddressInsufficientBalance(address account);\\n\\n /**\\n * @dev There's no code at `target` (it is not a contract).\\n */\\n error AddressEmptyCode(address target);\\n\\n /**\\n * @dev A call to an address target failed. The target may have reverted.\\n */\\n error FailedInnerCall();\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n if (address(this).balance < amount) {\\n revert AddressInsufficientBalance(address(this));\\n }\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n if (!success) {\\n revert FailedInnerCall();\\n }\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason or custom error, it is bubbled\\n * up by this function (like regular Solidity function calls). However, if\\n * the call reverted with no returned reason, this function reverts with a\\n * {FailedInnerCall} error.\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n */\\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\\n if (address(this).balance < value) {\\n revert AddressInsufficientBalance(address(this));\\n }\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a delegate call.\\n */\\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.delegatecall(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\\n * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\\n * unsuccessful call.\\n */\\n function verifyCallResultFromTarget(\\n address target,\\n bool success,\\n bytes memory returndata\\n ) internal view returns (bytes memory) {\\n if (!success) {\\n _revert(returndata);\\n } else {\\n // only check if target is a contract if the call was successful and the return data is empty\\n // otherwise we already know that it was a contract\\n if (returndata.length == 0 && target.code.length == 0) {\\n revert AddressEmptyCode(target);\\n }\\n return returndata;\\n }\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\\n * revert reason or with a default {FailedInnerCall} error.\\n */\\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\\n if (!success) {\\n _revert(returndata);\\n } else {\\n return returndata;\\n }\\n }\\n\\n /**\\n * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\\n */\\n function _revert(bytes memory returndata) private pure {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n /// @solidity memory-safe-assembly\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert FailedInnerCall();\\n }\\n }\\n}\\n\",\"keccak256\":\"0xaf28a975a78550e45f65e559a3ad6a5ad43b9b8a37366999abd1b7084eb70721\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Context.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Provides information about the current execution context, including the\\n * sender of the transaction and its data. While these are generally available\\n * via msg.sender and msg.data, they should not be accessed in such a direct\\n * manner, since when dealing with meta-transactions the account sending and\\n * paying for execution may not be the actual sender (as far as an application\\n * is concerned).\\n *\\n * This contract is only required for intermediate, library-like contracts.\\n */\\nabstract contract Context {\\n function _msgSender() internal view virtual returns (address) {\\n return msg.sender;\\n }\\n\\n function _msgData() internal view virtual returns (bytes calldata) {\\n return msg.data;\\n }\\n}\\n\",\"keccak256\":\"0x75a4ee64c68dbd5f38bddd06e664a64c8271b4caa554fb6f0607dfd672bb4bf3\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/math/Math.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Standard math utilities missing in the Solidity language.\\n */\\nlibrary Math {\\n /**\\n * @dev Muldiv operation overflow.\\n */\\n error MathOverflowedMulDiv();\\n\\n enum Rounding {\\n Floor, // Toward negative infinity\\n Ceil, // Toward positive infinity\\n Trunc, // Toward zero\\n Expand // Away from zero\\n }\\n\\n /**\\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\\n */\\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n uint256 c = a + b;\\n if (c < a) return (false, 0);\\n return (true, c);\\n }\\n }\\n\\n /**\\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\\n */\\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b > a) return (false, 0);\\n return (true, a - b);\\n }\\n }\\n\\n /**\\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\\n */\\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\\n // benefit is lost if 'b' is also tested.\\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\\n if (a == 0) return (true, 0);\\n uint256 c = a * b;\\n if (c / a != b) return (false, 0);\\n return (true, c);\\n }\\n }\\n\\n /**\\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\\n */\\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b == 0) return (false, 0);\\n return (true, a / b);\\n }\\n }\\n\\n /**\\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\\n */\\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b == 0) return (false, 0);\\n return (true, a % b);\\n }\\n }\\n\\n /**\\n * @dev Returns the largest of two numbers.\\n */\\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a > b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the smallest of two numbers.\\n */\\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a < b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the average of two numbers. The result is rounded towards\\n * zero.\\n */\\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\\n // (a + b) / 2 can overflow.\\n return (a & b) + (a ^ b) / 2;\\n }\\n\\n /**\\n * @dev Returns the ceiling of the division of two numbers.\\n *\\n * This differs from standard division with `/` in that it rounds towards infinity instead\\n * of rounding towards zero.\\n */\\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\\n if (b == 0) {\\n // Guarantee the same behavior as in a regular Solidity division.\\n return a / b;\\n }\\n\\n // (a + b - 1) / b can overflow on addition, so we distribute.\\n return a == 0 ? 0 : (a - 1) / b + 1;\\n }\\n\\n /**\\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\\n * denominator == 0.\\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\\n * Uniswap Labs also under MIT license.\\n */\\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\\n unchecked {\\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\\n // variables such that product = prod1 * 2^256 + prod0.\\n uint256 prod0 = x * y; // Least significant 256 bits of the product\\n uint256 prod1; // Most significant 256 bits of the product\\n assembly {\\n let mm := mulmod(x, y, not(0))\\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\\n }\\n\\n // Handle non-overflow cases, 256 by 256 division.\\n if (prod1 == 0) {\\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\\n // The surrounding unchecked block does not change this fact.\\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\\n return prod0 / denominator;\\n }\\n\\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\\n if (denominator <= prod1) {\\n revert MathOverflowedMulDiv();\\n }\\n\\n ///////////////////////////////////////////////\\n // 512 by 256 division.\\n ///////////////////////////////////////////////\\n\\n // Make division exact by subtracting the remainder from [prod1 prod0].\\n uint256 remainder;\\n assembly {\\n // Compute remainder using mulmod.\\n remainder := mulmod(x, y, denominator)\\n\\n // Subtract 256 bit number from 512 bit number.\\n prod1 := sub(prod1, gt(remainder, prod0))\\n prod0 := sub(prod0, remainder)\\n }\\n\\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\\n\\n uint256 twos = denominator & (0 - denominator);\\n assembly {\\n // Divide denominator by twos.\\n denominator := div(denominator, twos)\\n\\n // Divide [prod1 prod0] by twos.\\n prod0 := div(prod0, twos)\\n\\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\\n twos := add(div(sub(0, twos), twos), 1)\\n }\\n\\n // Shift in bits from prod1 into prod0.\\n prod0 |= prod1 * twos;\\n\\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\\n // four bits. That is, denominator * inv = 1 mod 2^4.\\n uint256 inverse = (3 * denominator) ^ 2;\\n\\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\\n // works in modular arithmetic, doubling the correct bits in each step.\\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\\n\\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\\n // is no longer required.\\n result = prod0 * inverse;\\n return result;\\n }\\n }\\n\\n /**\\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\\n */\\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\\n uint256 result = mulDiv(x, y, denominator);\\n if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\\n result += 1;\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\\n * towards zero.\\n *\\n * Inspired by Henry S. Warren, Jr.'s \\\"Hacker's Delight\\\" (Chapter 11).\\n */\\n function sqrt(uint256 a) internal pure returns (uint256) {\\n if (a == 0) {\\n return 0;\\n }\\n\\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\\n //\\n // We know that the \\\"msb\\\" (most significant bit) of our target number `a` is a power of 2 such that we have\\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\\n //\\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\\n // \\u2192 `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\\n // \\u2192 `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\\n //\\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\\n uint256 result = 1 << (log2(a) >> 1);\\n\\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\\n // into the expected uint128 result.\\n unchecked {\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n return min(result, a / result);\\n }\\n }\\n\\n /**\\n * @notice Calculates sqrt(a), following the selected rounding direction.\\n */\\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = sqrt(a);\\n return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 2 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 128;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 64;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 32;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 16;\\n }\\n if (value >> 8 > 0) {\\n value >>= 8;\\n result += 8;\\n }\\n if (value >> 4 > 0) {\\n value >>= 4;\\n result += 4;\\n }\\n if (value >> 2 > 0) {\\n value >>= 2;\\n result += 2;\\n }\\n if (value >> 1 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log2(value);\\n return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 10 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >= 10 ** 64) {\\n value /= 10 ** 64;\\n result += 64;\\n }\\n if (value >= 10 ** 32) {\\n value /= 10 ** 32;\\n result += 32;\\n }\\n if (value >= 10 ** 16) {\\n value /= 10 ** 16;\\n result += 16;\\n }\\n if (value >= 10 ** 8) {\\n value /= 10 ** 8;\\n result += 8;\\n }\\n if (value >= 10 ** 4) {\\n value /= 10 ** 4;\\n result += 4;\\n }\\n if (value >= 10 ** 2) {\\n value /= 10 ** 2;\\n result += 2;\\n }\\n if (value >= 10 ** 1) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log10(value);\\n return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 256 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n *\\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\\n */\\n function log256(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 16;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 8;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 4;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 2;\\n }\\n if (value >> 8 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log256(value);\\n return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\\n */\\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\\n return uint8(rounding) % 2 == 1;\\n }\\n}\\n\",\"keccak256\":\"0x005ec64c6313f0555d59e278f9a7a5ab2db5bdc72a027f255a37c327af1ec02d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/math/SafeCast.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)\\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\\n * checks.\\n *\\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\\n * easily result in undesired exploitation or bugs, since developers usually\\n * assume that overflows raise errors. `SafeCast` restores this intuition by\\n * reverting the transaction when such an operation overflows.\\n *\\n * Using this library instead of the unchecked operations eliminates an entire\\n * class of bugs, so it's recommended to use it always.\\n */\\nlibrary SafeCast {\\n /**\\n * @dev Value doesn't fit in an uint of `bits` size.\\n */\\n error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\\n\\n /**\\n * @dev An int value doesn't fit in an uint of `bits` size.\\n */\\n error SafeCastOverflowedIntToUint(int256 value);\\n\\n /**\\n * @dev Value doesn't fit in an int of `bits` size.\\n */\\n error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\\n\\n /**\\n * @dev An uint value doesn't fit in an int of `bits` size.\\n */\\n error SafeCastOverflowedUintToInt(uint256 value);\\n\\n /**\\n * @dev Returns the downcasted uint248 from uint256, reverting on\\n * overflow (when the input is greater than largest uint248).\\n *\\n * Counterpart to Solidity's `uint248` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 248 bits\\n */\\n function toUint248(uint256 value) internal pure returns (uint248) {\\n if (value > type(uint248).max) {\\n revert SafeCastOverflowedUintDowncast(248, value);\\n }\\n return uint248(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint240 from uint256, reverting on\\n * overflow (when the input is greater than largest uint240).\\n *\\n * Counterpart to Solidity's `uint240` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 240 bits\\n */\\n function toUint240(uint256 value) internal pure returns (uint240) {\\n if (value > type(uint240).max) {\\n revert SafeCastOverflowedUintDowncast(240, value);\\n }\\n return uint240(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint232 from uint256, reverting on\\n * overflow (when the input is greater than largest uint232).\\n *\\n * Counterpart to Solidity's `uint232` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 232 bits\\n */\\n function toUint232(uint256 value) internal pure returns (uint232) {\\n if (value > type(uint232).max) {\\n revert SafeCastOverflowedUintDowncast(232, value);\\n }\\n return uint232(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint224 from uint256, reverting on\\n * overflow (when the input is greater than largest uint224).\\n *\\n * Counterpart to Solidity's `uint224` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 224 bits\\n */\\n function toUint224(uint256 value) internal pure returns (uint224) {\\n if (value > type(uint224).max) {\\n revert SafeCastOverflowedUintDowncast(224, value);\\n }\\n return uint224(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint216 from uint256, reverting on\\n * overflow (when the input is greater than largest uint216).\\n *\\n * Counterpart to Solidity's `uint216` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 216 bits\\n */\\n function toUint216(uint256 value) internal pure returns (uint216) {\\n if (value > type(uint216).max) {\\n revert SafeCastOverflowedUintDowncast(216, value);\\n }\\n return uint216(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint208 from uint256, reverting on\\n * overflow (when the input is greater than largest uint208).\\n *\\n * Counterpart to Solidity's `uint208` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 208 bits\\n */\\n function toUint208(uint256 value) internal pure returns (uint208) {\\n if (value > type(uint208).max) {\\n revert SafeCastOverflowedUintDowncast(208, value);\\n }\\n return uint208(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint200 from uint256, reverting on\\n * overflow (when the input is greater than largest uint200).\\n *\\n * Counterpart to Solidity's `uint200` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 200 bits\\n */\\n function toUint200(uint256 value) internal pure returns (uint200) {\\n if (value > type(uint200).max) {\\n revert SafeCastOverflowedUintDowncast(200, value);\\n }\\n return uint200(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint192 from uint256, reverting on\\n * overflow (when the input is greater than largest uint192).\\n *\\n * Counterpart to Solidity's `uint192` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 192 bits\\n */\\n function toUint192(uint256 value) internal pure returns (uint192) {\\n if (value > type(uint192).max) {\\n revert SafeCastOverflowedUintDowncast(192, value);\\n }\\n return uint192(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint184 from uint256, reverting on\\n * overflow (when the input is greater than largest uint184).\\n *\\n * Counterpart to Solidity's `uint184` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 184 bits\\n */\\n function toUint184(uint256 value) internal pure returns (uint184) {\\n if (value > type(uint184).max) {\\n revert SafeCastOverflowedUintDowncast(184, value);\\n }\\n return uint184(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint176 from uint256, reverting on\\n * overflow (when the input is greater than largest uint176).\\n *\\n * Counterpart to Solidity's `uint176` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 176 bits\\n */\\n function toUint176(uint256 value) internal pure returns (uint176) {\\n if (value > type(uint176).max) {\\n revert SafeCastOverflowedUintDowncast(176, value);\\n }\\n return uint176(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint168 from uint256, reverting on\\n * overflow (when the input is greater than largest uint168).\\n *\\n * Counterpart to Solidity's `uint168` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 168 bits\\n */\\n function toUint168(uint256 value) internal pure returns (uint168) {\\n if (value > type(uint168).max) {\\n revert SafeCastOverflowedUintDowncast(168, value);\\n }\\n return uint168(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint160 from uint256, reverting on\\n * overflow (when the input is greater than largest uint160).\\n *\\n * Counterpart to Solidity's `uint160` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 160 bits\\n */\\n function toUint160(uint256 value) internal pure returns (uint160) {\\n if (value > type(uint160).max) {\\n revert SafeCastOverflowedUintDowncast(160, value);\\n }\\n return uint160(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint152 from uint256, reverting on\\n * overflow (when the input is greater than largest uint152).\\n *\\n * Counterpart to Solidity's `uint152` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 152 bits\\n */\\n function toUint152(uint256 value) internal pure returns (uint152) {\\n if (value > type(uint152).max) {\\n revert SafeCastOverflowedUintDowncast(152, value);\\n }\\n return uint152(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint144 from uint256, reverting on\\n * overflow (when the input is greater than largest uint144).\\n *\\n * Counterpart to Solidity's `uint144` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 144 bits\\n */\\n function toUint144(uint256 value) internal pure returns (uint144) {\\n if (value > type(uint144).max) {\\n revert SafeCastOverflowedUintDowncast(144, value);\\n }\\n return uint144(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint136 from uint256, reverting on\\n * overflow (when the input is greater than largest uint136).\\n *\\n * Counterpart to Solidity's `uint136` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 136 bits\\n */\\n function toUint136(uint256 value) internal pure returns (uint136) {\\n if (value > type(uint136).max) {\\n revert SafeCastOverflowedUintDowncast(136, value);\\n }\\n return uint136(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint128 from uint256, reverting on\\n * overflow (when the input is greater than largest uint128).\\n *\\n * Counterpart to Solidity's `uint128` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 128 bits\\n */\\n function toUint128(uint256 value) internal pure returns (uint128) {\\n if (value > type(uint128).max) {\\n revert SafeCastOverflowedUintDowncast(128, value);\\n }\\n return uint128(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint120 from uint256, reverting on\\n * overflow (when the input is greater than largest uint120).\\n *\\n * Counterpart to Solidity's `uint120` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 120 bits\\n */\\n function toUint120(uint256 value) internal pure returns (uint120) {\\n if (value > type(uint120).max) {\\n revert SafeCastOverflowedUintDowncast(120, value);\\n }\\n return uint120(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint112 from uint256, reverting on\\n * overflow (when the input is greater than largest uint112).\\n *\\n * Counterpart to Solidity's `uint112` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 112 bits\\n */\\n function toUint112(uint256 value) internal pure returns (uint112) {\\n if (value > type(uint112).max) {\\n revert SafeCastOverflowedUintDowncast(112, value);\\n }\\n return uint112(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint104 from uint256, reverting on\\n * overflow (when the input is greater than largest uint104).\\n *\\n * Counterpart to Solidity's `uint104` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 104 bits\\n */\\n function toUint104(uint256 value) internal pure returns (uint104) {\\n if (value > type(uint104).max) {\\n revert SafeCastOverflowedUintDowncast(104, value);\\n }\\n return uint104(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint96 from uint256, reverting on\\n * overflow (when the input is greater than largest uint96).\\n *\\n * Counterpart to Solidity's `uint96` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 96 bits\\n */\\n function toUint96(uint256 value) internal pure returns (uint96) {\\n if (value > type(uint96).max) {\\n revert SafeCastOverflowedUintDowncast(96, value);\\n }\\n return uint96(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint88 from uint256, reverting on\\n * overflow (when the input is greater than largest uint88).\\n *\\n * Counterpart to Solidity's `uint88` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 88 bits\\n */\\n function toUint88(uint256 value) internal pure returns (uint88) {\\n if (value > type(uint88).max) {\\n revert SafeCastOverflowedUintDowncast(88, value);\\n }\\n return uint88(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint80 from uint256, reverting on\\n * overflow (when the input is greater than largest uint80).\\n *\\n * Counterpart to Solidity's `uint80` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 80 bits\\n */\\n function toUint80(uint256 value) internal pure returns (uint80) {\\n if (value > type(uint80).max) {\\n revert SafeCastOverflowedUintDowncast(80, value);\\n }\\n return uint80(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint72 from uint256, reverting on\\n * overflow (when the input is greater than largest uint72).\\n *\\n * Counterpart to Solidity's `uint72` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 72 bits\\n */\\n function toUint72(uint256 value) internal pure returns (uint72) {\\n if (value > type(uint72).max) {\\n revert SafeCastOverflowedUintDowncast(72, value);\\n }\\n return uint72(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint64 from uint256, reverting on\\n * overflow (when the input is greater than largest uint64).\\n *\\n * Counterpart to Solidity's `uint64` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 64 bits\\n */\\n function toUint64(uint256 value) internal pure returns (uint64) {\\n if (value > type(uint64).max) {\\n revert SafeCastOverflowedUintDowncast(64, value);\\n }\\n return uint64(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint56 from uint256, reverting on\\n * overflow (when the input is greater than largest uint56).\\n *\\n * Counterpart to Solidity's `uint56` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 56 bits\\n */\\n function toUint56(uint256 value) internal pure returns (uint56) {\\n if (value > type(uint56).max) {\\n revert SafeCastOverflowedUintDowncast(56, value);\\n }\\n return uint56(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint48 from uint256, reverting on\\n * overflow (when the input is greater than largest uint48).\\n *\\n * Counterpart to Solidity's `uint48` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 48 bits\\n */\\n function toUint48(uint256 value) internal pure returns (uint48) {\\n if (value > type(uint48).max) {\\n revert SafeCastOverflowedUintDowncast(48, value);\\n }\\n return uint48(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint40 from uint256, reverting on\\n * overflow (when the input is greater than largest uint40).\\n *\\n * Counterpart to Solidity's `uint40` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 40 bits\\n */\\n function toUint40(uint256 value) internal pure returns (uint40) {\\n if (value > type(uint40).max) {\\n revert SafeCastOverflowedUintDowncast(40, value);\\n }\\n return uint40(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint32 from uint256, reverting on\\n * overflow (when the input is greater than largest uint32).\\n *\\n * Counterpart to Solidity's `uint32` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 32 bits\\n */\\n function toUint32(uint256 value) internal pure returns (uint32) {\\n if (value > type(uint32).max) {\\n revert SafeCastOverflowedUintDowncast(32, value);\\n }\\n return uint32(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint24 from uint256, reverting on\\n * overflow (when the input is greater than largest uint24).\\n *\\n * Counterpart to Solidity's `uint24` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 24 bits\\n */\\n function toUint24(uint256 value) internal pure returns (uint24) {\\n if (value > type(uint24).max) {\\n revert SafeCastOverflowedUintDowncast(24, value);\\n }\\n return uint24(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint16 from uint256, reverting on\\n * overflow (when the input is greater than largest uint16).\\n *\\n * Counterpart to Solidity's `uint16` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 16 bits\\n */\\n function toUint16(uint256 value) internal pure returns (uint16) {\\n if (value > type(uint16).max) {\\n revert SafeCastOverflowedUintDowncast(16, value);\\n }\\n return uint16(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted uint8 from uint256, reverting on\\n * overflow (when the input is greater than largest uint8).\\n *\\n * Counterpart to Solidity's `uint8` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 8 bits\\n */\\n function toUint8(uint256 value) internal pure returns (uint8) {\\n if (value > type(uint8).max) {\\n revert SafeCastOverflowedUintDowncast(8, value);\\n }\\n return uint8(value);\\n }\\n\\n /**\\n * @dev Converts a signed int256 into an unsigned uint256.\\n *\\n * Requirements:\\n *\\n * - input must be greater than or equal to 0.\\n */\\n function toUint256(int256 value) internal pure returns (uint256) {\\n if (value < 0) {\\n revert SafeCastOverflowedIntToUint(value);\\n }\\n return uint256(value);\\n }\\n\\n /**\\n * @dev Returns the downcasted int248 from int256, reverting on\\n * overflow (when the input is less than smallest int248 or\\n * greater than largest int248).\\n *\\n * Counterpart to Solidity's `int248` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 248 bits\\n */\\n function toInt248(int256 value) internal pure returns (int248 downcasted) {\\n downcasted = int248(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(248, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int240 from int256, reverting on\\n * overflow (when the input is less than smallest int240 or\\n * greater than largest int240).\\n *\\n * Counterpart to Solidity's `int240` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 240 bits\\n */\\n function toInt240(int256 value) internal pure returns (int240 downcasted) {\\n downcasted = int240(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(240, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int232 from int256, reverting on\\n * overflow (when the input is less than smallest int232 or\\n * greater than largest int232).\\n *\\n * Counterpart to Solidity's `int232` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 232 bits\\n */\\n function toInt232(int256 value) internal pure returns (int232 downcasted) {\\n downcasted = int232(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(232, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int224 from int256, reverting on\\n * overflow (when the input is less than smallest int224 or\\n * greater than largest int224).\\n *\\n * Counterpart to Solidity's `int224` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 224 bits\\n */\\n function toInt224(int256 value) internal pure returns (int224 downcasted) {\\n downcasted = int224(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(224, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int216 from int256, reverting on\\n * overflow (when the input is less than smallest int216 or\\n * greater than largest int216).\\n *\\n * Counterpart to Solidity's `int216` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 216 bits\\n */\\n function toInt216(int256 value) internal pure returns (int216 downcasted) {\\n downcasted = int216(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(216, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int208 from int256, reverting on\\n * overflow (when the input is less than smallest int208 or\\n * greater than largest int208).\\n *\\n * Counterpart to Solidity's `int208` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 208 bits\\n */\\n function toInt208(int256 value) internal pure returns (int208 downcasted) {\\n downcasted = int208(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(208, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int200 from int256, reverting on\\n * overflow (when the input is less than smallest int200 or\\n * greater than largest int200).\\n *\\n * Counterpart to Solidity's `int200` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 200 bits\\n */\\n function toInt200(int256 value) internal pure returns (int200 downcasted) {\\n downcasted = int200(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(200, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int192 from int256, reverting on\\n * overflow (when the input is less than smallest int192 or\\n * greater than largest int192).\\n *\\n * Counterpart to Solidity's `int192` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 192 bits\\n */\\n function toInt192(int256 value) internal pure returns (int192 downcasted) {\\n downcasted = int192(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(192, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int184 from int256, reverting on\\n * overflow (when the input is less than smallest int184 or\\n * greater than largest int184).\\n *\\n * Counterpart to Solidity's `int184` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 184 bits\\n */\\n function toInt184(int256 value) internal pure returns (int184 downcasted) {\\n downcasted = int184(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(184, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int176 from int256, reverting on\\n * overflow (when the input is less than smallest int176 or\\n * greater than largest int176).\\n *\\n * Counterpart to Solidity's `int176` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 176 bits\\n */\\n function toInt176(int256 value) internal pure returns (int176 downcasted) {\\n downcasted = int176(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(176, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int168 from int256, reverting on\\n * overflow (when the input is less than smallest int168 or\\n * greater than largest int168).\\n *\\n * Counterpart to Solidity's `int168` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 168 bits\\n */\\n function toInt168(int256 value) internal pure returns (int168 downcasted) {\\n downcasted = int168(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(168, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int160 from int256, reverting on\\n * overflow (when the input is less than smallest int160 or\\n * greater than largest int160).\\n *\\n * Counterpart to Solidity's `int160` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 160 bits\\n */\\n function toInt160(int256 value) internal pure returns (int160 downcasted) {\\n downcasted = int160(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(160, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int152 from int256, reverting on\\n * overflow (when the input is less than smallest int152 or\\n * greater than largest int152).\\n *\\n * Counterpart to Solidity's `int152` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 152 bits\\n */\\n function toInt152(int256 value) internal pure returns (int152 downcasted) {\\n downcasted = int152(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(152, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int144 from int256, reverting on\\n * overflow (when the input is less than smallest int144 or\\n * greater than largest int144).\\n *\\n * Counterpart to Solidity's `int144` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 144 bits\\n */\\n function toInt144(int256 value) internal pure returns (int144 downcasted) {\\n downcasted = int144(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(144, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int136 from int256, reverting on\\n * overflow (when the input is less than smallest int136 or\\n * greater than largest int136).\\n *\\n * Counterpart to Solidity's `int136` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 136 bits\\n */\\n function toInt136(int256 value) internal pure returns (int136 downcasted) {\\n downcasted = int136(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(136, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int128 from int256, reverting on\\n * overflow (when the input is less than smallest int128 or\\n * greater than largest int128).\\n *\\n * Counterpart to Solidity's `int128` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 128 bits\\n */\\n function toInt128(int256 value) internal pure returns (int128 downcasted) {\\n downcasted = int128(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(128, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int120 from int256, reverting on\\n * overflow (when the input is less than smallest int120 or\\n * greater than largest int120).\\n *\\n * Counterpart to Solidity's `int120` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 120 bits\\n */\\n function toInt120(int256 value) internal pure returns (int120 downcasted) {\\n downcasted = int120(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(120, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int112 from int256, reverting on\\n * overflow (when the input is less than smallest int112 or\\n * greater than largest int112).\\n *\\n * Counterpart to Solidity's `int112` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 112 bits\\n */\\n function toInt112(int256 value) internal pure returns (int112 downcasted) {\\n downcasted = int112(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(112, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int104 from int256, reverting on\\n * overflow (when the input is less than smallest int104 or\\n * greater than largest int104).\\n *\\n * Counterpart to Solidity's `int104` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 104 bits\\n */\\n function toInt104(int256 value) internal pure returns (int104 downcasted) {\\n downcasted = int104(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(104, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int96 from int256, reverting on\\n * overflow (when the input is less than smallest int96 or\\n * greater than largest int96).\\n *\\n * Counterpart to Solidity's `int96` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 96 bits\\n */\\n function toInt96(int256 value) internal pure returns (int96 downcasted) {\\n downcasted = int96(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(96, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int88 from int256, reverting on\\n * overflow (when the input is less than smallest int88 or\\n * greater than largest int88).\\n *\\n * Counterpart to Solidity's `int88` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 88 bits\\n */\\n function toInt88(int256 value) internal pure returns (int88 downcasted) {\\n downcasted = int88(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(88, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int80 from int256, reverting on\\n * overflow (when the input is less than smallest int80 or\\n * greater than largest int80).\\n *\\n * Counterpart to Solidity's `int80` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 80 bits\\n */\\n function toInt80(int256 value) internal pure returns (int80 downcasted) {\\n downcasted = int80(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(80, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int72 from int256, reverting on\\n * overflow (when the input is less than smallest int72 or\\n * greater than largest int72).\\n *\\n * Counterpart to Solidity's `int72` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 72 bits\\n */\\n function toInt72(int256 value) internal pure returns (int72 downcasted) {\\n downcasted = int72(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(72, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int64 from int256, reverting on\\n * overflow (when the input is less than smallest int64 or\\n * greater than largest int64).\\n *\\n * Counterpart to Solidity's `int64` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 64 bits\\n */\\n function toInt64(int256 value) internal pure returns (int64 downcasted) {\\n downcasted = int64(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(64, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int56 from int256, reverting on\\n * overflow (when the input is less than smallest int56 or\\n * greater than largest int56).\\n *\\n * Counterpart to Solidity's `int56` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 56 bits\\n */\\n function toInt56(int256 value) internal pure returns (int56 downcasted) {\\n downcasted = int56(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(56, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int48 from int256, reverting on\\n * overflow (when the input is less than smallest int48 or\\n * greater than largest int48).\\n *\\n * Counterpart to Solidity's `int48` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 48 bits\\n */\\n function toInt48(int256 value) internal pure returns (int48 downcasted) {\\n downcasted = int48(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(48, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int40 from int256, reverting on\\n * overflow (when the input is less than smallest int40 or\\n * greater than largest int40).\\n *\\n * Counterpart to Solidity's `int40` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 40 bits\\n */\\n function toInt40(int256 value) internal pure returns (int40 downcasted) {\\n downcasted = int40(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(40, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int32 from int256, reverting on\\n * overflow (when the input is less than smallest int32 or\\n * greater than largest int32).\\n *\\n * Counterpart to Solidity's `int32` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 32 bits\\n */\\n function toInt32(int256 value) internal pure returns (int32 downcasted) {\\n downcasted = int32(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(32, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int24 from int256, reverting on\\n * overflow (when the input is less than smallest int24 or\\n * greater than largest int24).\\n *\\n * Counterpart to Solidity's `int24` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 24 bits\\n */\\n function toInt24(int256 value) internal pure returns (int24 downcasted) {\\n downcasted = int24(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(24, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int16 from int256, reverting on\\n * overflow (when the input is less than smallest int16 or\\n * greater than largest int16).\\n *\\n * Counterpart to Solidity's `int16` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 16 bits\\n */\\n function toInt16(int256 value) internal pure returns (int16 downcasted) {\\n downcasted = int16(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(16, value);\\n }\\n }\\n\\n /**\\n * @dev Returns the downcasted int8 from int256, reverting on\\n * overflow (when the input is less than smallest int8 or\\n * greater than largest int8).\\n *\\n * Counterpart to Solidity's `int8` operator.\\n *\\n * Requirements:\\n *\\n * - input must fit into 8 bits\\n */\\n function toInt8(int256 value) internal pure returns (int8 downcasted) {\\n downcasted = int8(value);\\n if (downcasted != value) {\\n revert SafeCastOverflowedIntDowncast(8, value);\\n }\\n }\\n\\n /**\\n * @dev Converts an unsigned uint256 into a signed int256.\\n *\\n * Requirements:\\n *\\n * - input must be less than or equal to maxInt256.\\n */\\n function toInt256(uint256 value) internal pure returns (int256) {\\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\\n if (value > uint256(type(int256).max)) {\\n revert SafeCastOverflowedUintToInt(value);\\n }\\n return int256(value);\\n }\\n}\\n\",\"keccak256\":\"0xe19a4d5f31d2861e7344e8e535e2feafb913d806d3e2b5fe7782741a2a7094fe\",\"license\":\"MIT\"},\"contracts/AcreBitcoinDepositor.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/access/Ownable2Step.sol\\\";\\nimport {SafeERC20} from \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport {IERC20} from \\\"@openzeppelin/contracts/token/ERC20/IERC20.sol\\\";\\nimport {SafeCast} from \\\"@openzeppelin/contracts/utils/math/SafeCast.sol\\\";\\n\\nimport \\\"@keep-network/tbtc-v2/contracts/integrator/AbstractTBTCDepositor.sol\\\";\\n\\nimport {stBTC} from \\\"./stBTC.sol\\\";\\n\\n// TODO: Make Upgradable\\n// TODO: Make Pausable\\n\\n/// @title Acre Bitcoin Depositor contract.\\n/// @notice The contract integrates Acre staking with tBTC minting.\\n/// User who wants to stake BTC in Acre should submit a Bitcoin transaction\\n/// to the most recently created off-chain ECDSA wallets of the tBTC Bridge\\n/// using pay-to-script-hash (P2SH) or pay-to-witness-script-hash (P2WSH)\\n/// containing hashed information about this Depositor contract address,\\n/// and staker's Ethereum address.\\n/// Then, the staker initiates tBTC minting by revealing their Ethereum\\n/// address along with their deposit blinding factor, refund public key\\n/// hash and refund locktime on the tBTC Bridge through this Depositor\\n/// contract.\\n/// The off-chain ECDSA wallet and Optimistic Minting bots listen for these\\n/// sorts of messages and when they get one, they check the Bitcoin network\\n/// to make sure the deposit lines up. Majority of tBTC minting is finalized\\n/// by the Optimistic Minting process, where Minter bot initializes\\n/// minting process and if there is no veto from the Guardians, the\\n/// process is finalized and tBTC minted to the Depositor address. If\\n/// the revealed deposit is not handled by the Optimistic Minting process\\n/// the off-chain ECDSA wallet may decide to pick the deposit transaction\\n/// for sweeping, and when the sweep operation is confirmed on the Bitcoin\\n/// network, the tBTC Bridge and tBTC vault mint the tBTC token to the\\n/// Depositor address. After tBTC is minted to the Depositor, on the stake\\n/// finalization tBTC is staked in stBTC contract and stBTC shares are emitted\\n/// to the staker.\\ncontract AcreBitcoinDepositor is AbstractTBTCDepositor, Ownable2Step {\\n using SafeERC20 for IERC20;\\n\\n /// @notice State of the stake request.\\n enum StakeRequestState {\\n Unknown,\\n Initialized,\\n Finalized,\\n Queued,\\n FinalizedFromQueue,\\n CancelledFromQueue\\n }\\n\\n struct StakeRequest {\\n // State of the stake request.\\n StakeRequestState state;\\n // The address to which the stBTC shares will be minted. Stored only when\\n // request is queued.\\n address staker;\\n // tBTC token amount to stake after deducting tBTC minting fees and the\\n // Depositor fee. Stored only when request is queued.\\n uint88 queuedAmount;\\n }\\n\\n /// @notice Mapping of stake requests.\\n /// @dev The key is a deposit key identifying the deposit.\\n mapping(uint256 => StakeRequest) public stakeRequests;\\n\\n /// @notice tBTC Token contract.\\n // TODO: Remove slither disable when introducing upgradeability.\\n // slither-disable-next-line immutable-states\\n IERC20 public tbtcToken;\\n\\n /// @notice stBTC contract.\\n // TODO: Remove slither disable when introducing upgradeability.\\n // slither-disable-next-line immutable-states\\n stBTC public stbtc;\\n\\n /// @notice Divisor used to compute the depositor fee taken from each deposit\\n /// and transferred to the treasury upon stake request finalization.\\n /// @dev That fee is computed as follows:\\n /// `depositorFee = depositedAmount / depositorFeeDivisor`\\n /// for example, if the depositor fee needs to be 2% of each deposit,\\n /// the `depositorFeeDivisor` should be set to `50` because\\n /// `1/50 = 0.02 = 2%`.\\n uint64 public depositorFeeDivisor;\\n\\n /// @notice Emitted when a stake request is initialized.\\n /// @dev Deposit details can be fetched from {{ Bridge.DepositRevealed }}\\n /// event emitted in the same transaction.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param caller Address that initialized the stake request.\\n /// @param staker The address to which the stBTC shares will be minted.\\n event StakeRequestInitialized(\\n uint256 indexed depositKey,\\n address indexed caller,\\n address indexed staker\\n );\\n\\n /// @notice Emitted when bridging completion has been notified.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param caller Address that notified about bridging completion.\\n /// @param referral Identifier of a partner in the referral program.\\n /// @param bridgedAmount Amount of tBTC tokens that was bridged by the tBTC bridge.\\n /// @param depositorFee Depositor fee amount.\\n event BridgingCompleted(\\n uint256 indexed depositKey,\\n address indexed caller,\\n uint16 indexed referral,\\n uint256 bridgedAmount,\\n uint256 depositorFee\\n );\\n\\n /// @notice Emitted when a stake request is finalized.\\n /// @dev Deposit details can be fetched from {{ ERC4626.Deposit }}\\n /// event emitted in the same transaction.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param caller Address that finalized the stake request.\\n /// @param stakedAmount Amount of staked tBTC tokens.\\n event StakeRequestFinalized(\\n uint256 indexed depositKey,\\n address indexed caller,\\n uint256 stakedAmount\\n );\\n\\n /// @notice Emitted when a stake request is queued.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param caller Address that finalized the stake request.\\n /// @param queuedAmount Amount of queued tBTC tokens.\\n event StakeRequestQueued(\\n uint256 indexed depositKey,\\n address indexed caller,\\n uint256 queuedAmount\\n );\\n\\n /// @notice Emitted when a stake request is finalized from the queue.\\n /// @dev Deposit details can be fetched from {{ ERC4626.Deposit }}\\n /// event emitted in the same transaction.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param caller Address that finalized the stake request.\\n /// @param stakedAmount Amount of staked tBTC tokens.\\n event StakeRequestFinalizedFromQueue(\\n uint256 indexed depositKey,\\n address indexed caller,\\n uint256 stakedAmount\\n );\\n\\n /// @notice Emitted when a queued stake request is cancelled.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param staker Address of the staker.\\n /// @param amountToStake Amount of queued tBTC tokens that got cancelled.\\n event StakeRequestCancelledFromQueue(\\n uint256 indexed depositKey,\\n address indexed staker,\\n uint256 amountToStake\\n );\\n\\n /// @notice Emitted when a depositor fee divisor is updated.\\n /// @param depositorFeeDivisor New value of the depositor fee divisor.\\n event DepositorFeeDivisorUpdated(uint64 depositorFeeDivisor);\\n\\n /// Reverts if the tBTC Token address is zero.\\n error TbtcTokenZeroAddress();\\n\\n /// Reverts if the stBTC address is zero.\\n error StbtcZeroAddress();\\n\\n /// @dev Staker address is zero.\\n error StakerIsZeroAddress();\\n\\n /// @dev Attempted to execute function for stake request in unexpected current\\n /// state.\\n error UnexpectedStakeRequestState(\\n StakeRequestState currentState,\\n StakeRequestState expectedState\\n );\\n\\n /// @dev Attempted to finalize bridging with depositor's contract tBTC balance\\n /// lower than the calculated bridged tBTC amount. This error means\\n /// that Governance should top-up the tBTC reserve for bridging fees\\n /// approximation.\\n error InsufficientTbtcBalance(\\n uint256 amountToStake,\\n uint256 currentBalance\\n );\\n\\n /// @dev Attempted to notify a bridging completion, while it was already\\n /// notified.\\n error BridgingCompletionAlreadyNotified();\\n\\n /// @dev Attempted to finalize a stake request, while bridging completion has\\n /// not been notified yet.\\n error BridgingNotCompleted();\\n\\n /// @dev Calculated depositor fee exceeds the amount of minted tBTC tokens.\\n error DepositorFeeExceedsBridgedAmount(\\n uint256 depositorFee,\\n uint256 bridgedAmount\\n );\\n\\n /// @dev Attempted to call bridging finalization for a stake request for\\n /// which the function was already called.\\n error BridgingFinalizationAlreadyCalled();\\n\\n /// @dev Attempted to finalize or cancel a stake request that was not added\\n /// to the queue, or was already finalized or cancelled.\\n error StakeRequestNotQueued();\\n\\n /// @dev Attempted to call function by an account that is not the staker.\\n error CallerNotStaker();\\n\\n /// @notice Acre Bitcoin Depositor contract constructor.\\n /// @param bridge tBTC Bridge contract instance.\\n /// @param tbtcVault tBTC Vault contract instance.\\n /// @param _tbtcToken tBTC token contract instance.\\n /// @param _stbtc stBTC contract instance.\\n // TODO: Move to initializer when making the contract upgradeable.\\n constructor(\\n address bridge,\\n address tbtcVault,\\n address _tbtcToken,\\n address _stbtc\\n ) Ownable(msg.sender) {\\n __AbstractTBTCDepositor_initialize(bridge, tbtcVault);\\n\\n if (address(_tbtcToken) == address(0)) {\\n revert TbtcTokenZeroAddress();\\n }\\n if (address(_stbtc) == address(0)) {\\n revert StbtcZeroAddress();\\n }\\n\\n tbtcToken = IERC20(_tbtcToken);\\n stbtc = stBTC(_stbtc);\\n\\n depositorFeeDivisor = 1000; // 1/1000 == 10bps == 0.1% == 0.001\\n }\\n\\n /// @notice This function allows staking process initialization for a Bitcoin\\n /// deposit made by an user with a P2(W)SH transaction. It uses the\\n /// supplied information to reveal a deposit to the tBTC Bridge contract.\\n /// @dev Requirements:\\n /// - The revealed vault address must match the TBTCVault address,\\n /// - All requirements from {Bridge#revealDepositWithExtraData}\\n /// function must be met.\\n /// - `staker` must be the staker address used in the P2(W)SH BTC\\n /// deposit transaction as part of the extra data.\\n /// - `referral` must be the referral info used in the P2(W)SH BTC\\n /// deposit transaction as part of the extra data.\\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\\n /// can be revealed only one time.\\n /// @param fundingTx Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.\\n /// @param reveal Deposit reveal data, see `IBridgeTypes.DepositRevealInfo`.\\n /// @param staker The address to which the stBTC shares will be minted.\\n /// @param referral Data used for referral program.\\n function initializeStake(\\n IBridgeTypes.BitcoinTxInfo calldata fundingTx,\\n IBridgeTypes.DepositRevealInfo calldata reveal,\\n address staker,\\n uint16 referral\\n ) external {\\n if (staker == address(0)) revert StakerIsZeroAddress();\\n\\n // We don't check if the request was already initialized, as this check\\n // is enforced in `_initializeDeposit` when calling the\\n // `Bridge.revealDepositWithExtraData` function.\\n uint256 depositKey = _initializeDeposit(\\n fundingTx,\\n reveal,\\n encodeExtraData(staker, referral)\\n );\\n\\n transitionStakeRequestState(\\n depositKey,\\n StakeRequestState.Unknown,\\n StakeRequestState.Initialized\\n );\\n\\n emit StakeRequestInitialized(depositKey, msg.sender, staker);\\n }\\n\\n /// @notice This function should be called for previously initialized stake\\n /// request, after tBTC bridging process was finalized.\\n /// It stakes the tBTC from the given deposit into stBTC, emitting the\\n /// stBTC shares to the staker specified in the deposit extra data\\n /// and using the referral provided in the extra data.\\n /// @dev In case depositing in stBTC vault fails (e.g. because of the\\n /// maximum deposit limit being reached), the `queueStake` function\\n /// should be called to add the stake request to the staking queue.\\n /// @param depositKey Deposit key identifying the deposit.\\n function finalizeStake(uint256 depositKey) external {\\n transitionStakeRequestState(\\n depositKey,\\n StakeRequestState.Initialized,\\n StakeRequestState.Finalized\\n );\\n\\n (uint256 amountToStake, address staker) = finalizeBridging(depositKey);\\n\\n emit StakeRequestFinalized(depositKey, msg.sender, amountToStake);\\n\\n // Deposit tBTC in stBTC.\\n tbtcToken.safeIncreaseAllowance(address(stbtc), amountToStake);\\n // slither-disable-next-line unused-return\\n stbtc.deposit(amountToStake, staker);\\n }\\n\\n /// @notice This function should be called for previously initialized stake\\n /// request, after tBTC bridging process was finalized, in case the\\n /// `finalizeStake` failed due to stBTC vault deposit limit\\n /// being reached.\\n /// @dev It queues the stake request, until the stBTC vault is ready to\\n /// accept the deposit. The request must be finalized with `finalizeQueuedStake`\\n /// after the limit is increased or other user withdraws their funds\\n /// from the stBTC contract to make place for another deposit.\\n /// The staker has a possibility to submit `cancelQueuedStake` that\\n /// will withdraw the minted tBTC token and abort staking process.\\n /// @param depositKey Deposit key identifying the deposit.\\n function queueStake(uint256 depositKey) external {\\n transitionStakeRequestState(\\n depositKey,\\n StakeRequestState.Initialized,\\n StakeRequestState.Queued\\n );\\n\\n StakeRequest storage request = stakeRequests[depositKey];\\n\\n uint256 amountToStake;\\n (amountToStake, request.staker) = finalizeBridging(depositKey);\\n\\n request.queuedAmount = SafeCast.toUint88(amountToStake);\\n\\n emit StakeRequestQueued(depositKey, msg.sender, request.queuedAmount);\\n }\\n\\n /// @notice This function should be called for previously queued stake\\n /// request, when stBTC vault is able to accept a deposit.\\n /// @param depositKey Deposit key identifying the deposit.\\n function finalizeQueuedStake(uint256 depositKey) external {\\n transitionStakeRequestState(\\n depositKey,\\n StakeRequestState.Queued,\\n StakeRequestState.FinalizedFromQueue\\n );\\n\\n StakeRequest storage request = stakeRequests[depositKey];\\n\\n if (request.queuedAmount == 0) revert StakeRequestNotQueued();\\n\\n uint256 amountToStake = request.queuedAmount;\\n delete (request.queuedAmount);\\n\\n emit StakeRequestFinalizedFromQueue(\\n depositKey,\\n msg.sender,\\n amountToStake\\n );\\n\\n // Deposit tBTC in stBTC.\\n tbtcToken.safeIncreaseAllowance(address(stbtc), amountToStake);\\n // slither-disable-next-line unused-return\\n stbtc.deposit(amountToStake, request.staker);\\n }\\n\\n /// @notice Cancel queued stake.\\n /// The function can be called by the staker to recover tBTC that cannot\\n /// be finalized to stake in stBTC contract due to a deposit limit being\\n /// reached.\\n /// @dev This function can be called only after the stake request was added\\n /// to queue.\\n /// @dev Only staker provided in the extra data of the stake request can\\n /// call this function.\\n /// @param depositKey Deposit key identifying the deposit.\\n function cancelQueuedStake(uint256 depositKey) external {\\n transitionStakeRequestState(\\n depositKey,\\n StakeRequestState.Queued,\\n StakeRequestState.CancelledFromQueue\\n );\\n\\n StakeRequest storage request = stakeRequests[depositKey];\\n\\n if (request.queuedAmount == 0) revert StakeRequestNotQueued();\\n\\n // Check if caller is the staker.\\n if (msg.sender != request.staker) revert CallerNotStaker();\\n\\n uint256 amount = request.queuedAmount;\\n delete (request.queuedAmount);\\n\\n emit StakeRequestCancelledFromQueue(depositKey, request.staker, amount);\\n\\n tbtcToken.safeTransfer(request.staker, amount);\\n }\\n\\n /// @notice Updates the depositor fee divisor.\\n /// @param newDepositorFeeDivisor New depositor fee divisor value.\\n function updateDepositorFeeDivisor(\\n uint64 newDepositorFeeDivisor\\n ) external onlyOwner {\\n // TODO: Introduce a parameters update process.\\n depositorFeeDivisor = newDepositorFeeDivisor;\\n\\n emit DepositorFeeDivisorUpdated(newDepositorFeeDivisor);\\n }\\n\\n // TODO: Handle minimum deposit amount in tBTC Bridge vs stBTC.\\n\\n /// @notice Encodes staker address and referral as extra data.\\n /// @dev Packs the data to bytes32: 20 bytes of staker address and\\n /// 2 bytes of referral, 10 bytes of trailing zeros.\\n /// @param staker The address to which the stBTC shares will be minted.\\n /// @param referral Data used for referral program.\\n /// @return Encoded extra data.\\n function encodeExtraData(\\n address staker,\\n uint16 referral\\n ) public pure returns (bytes32) {\\n return bytes32(abi.encodePacked(staker, referral));\\n }\\n\\n /// @notice Decodes staker address and referral from extra data.\\n /// @dev Unpacks the data from bytes32: 20 bytes of staker address and\\n /// 2 bytes of referral, 10 bytes of trailing zeros.\\n /// @param extraData Encoded extra data.\\n /// @return staker The address to which the stBTC shares will be minted.\\n /// @return referral Data used for referral program.\\n function decodeExtraData(\\n bytes32 extraData\\n ) public pure returns (address staker, uint16 referral) {\\n // First 20 bytes of extra data is staker address.\\n staker = address(uint160(bytes20(extraData)));\\n // Next 2 bytes of extra data is referral info.\\n referral = uint16(bytes2(extraData << (8 * 20)));\\n }\\n\\n /// @notice This function is used for state transitions. It ensures the current\\n /// stakte matches expected, and updates the stake request to a new\\n /// state.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @param expectedState Expected current stake request state.\\n /// @param newState New stake request state.\\n function transitionStakeRequestState(\\n uint256 depositKey,\\n StakeRequestState expectedState,\\n StakeRequestState newState\\n ) internal {\\n // Validate current stake request state.\\n if (stakeRequests[depositKey].state != expectedState)\\n revert UnexpectedStakeRequestState(\\n stakeRequests[depositKey].state,\\n expectedState\\n );\\n\\n // Transition to a new state.\\n stakeRequests[depositKey].state = newState;\\n }\\n\\n /// @notice This function should be called for previously initialized stake\\n /// request, after tBTC minting process completed, meaning tBTC was\\n /// minted to this contract.\\n /// @dev It calculates the amount to stake based on the approximate minted\\n /// tBTC amount reduced by the depositor fee.\\n /// @dev IMPORTANT NOTE: The minted tBTC amount used by this function is an\\n /// approximation. See documentation of the\\n /// {{AbstractTBTCDepositor#_calculateTbtcAmount}} responsible for calculating\\n /// this value for more details.\\n /// @dev In case balance of tBTC tokens in this contract doesn't meet the\\n /// calculated tBTC amount, the function reverts with `InsufficientTbtcBalance`\\n /// error. This case requires Governance's validation, as tBTC Bridge minting\\n /// fees might changed in the way that reserve mentioned in\\n /// {{AbstractTBTCDepositor#_calculateTbtcAmount}} needs a top-up.\\n /// @param depositKey Deposit key identifying the deposit.\\n /// @return amountToStake tBTC token amount to stake after deducting tBTC bridging\\n /// fees and the depositor fee.\\n /// @return staker The address to which the stBTC shares will be minted.\\n function finalizeBridging(\\n uint256 depositKey\\n ) internal returns (uint256, address) {\\n (\\n uint256 initialDepositAmount,\\n uint256 tbtcAmount,\\n bytes32 extraData\\n ) = _finalizeDeposit(depositKey);\\n\\n // Check if current balance is sufficient to finalize bridging of `tbtcAmount`.\\n uint256 currentBalance = tbtcToken.balanceOf(address(this));\\n if (tbtcAmount > tbtcToken.balanceOf(address(this))) {\\n revert InsufficientTbtcBalance(tbtcAmount, currentBalance);\\n }\\n\\n // Compute depositor fee. The fee is calculated based on the initial funding\\n // transaction amount, before the tBTC protocol network fees were taken.\\n uint256 depositorFee = depositorFeeDivisor > 0\\n ? (initialDepositAmount / depositorFeeDivisor)\\n : 0;\\n\\n // Ensure the depositor fee does not exceed the approximate minted tBTC\\n // amount.\\n if (depositorFee >= tbtcAmount) {\\n revert DepositorFeeExceedsBridgedAmount(depositorFee, tbtcAmount);\\n }\\n\\n uint256 amountToStake = tbtcAmount - depositorFee;\\n\\n (address staker, uint16 referral) = decodeExtraData(extraData);\\n\\n // Emit event for accounting purposes to track partner's referral ID and\\n // depositor fee taken.\\n emit BridgingCompleted(\\n depositKey,\\n msg.sender,\\n referral,\\n tbtcAmount,\\n depositorFee\\n );\\n\\n // Transfer depositor fee to the treasury wallet.\\n if (depositorFee > 0) {\\n tbtcToken.safeTransfer(stbtc.treasury(), depositorFee);\\n }\\n\\n return (amountToStake, staker);\\n }\\n}\\n\",\"keccak256\":\"0x35f811a27cfb344b8153534c7e72388516e11de67f67179c467da0ad6c711711\",\"license\":\"GPL-3.0-only\"},\"contracts/Dispatcher.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/access/Ownable2Step.sol\\\";\\nimport \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport \\\"@openzeppelin/contracts/interfaces/IERC4626.sol\\\";\\nimport \\\"./Router.sol\\\";\\nimport \\\"./stBTC.sol\\\";\\n\\n/// @title Dispatcher\\n/// @notice Dispatcher is a contract that routes tBTC from stBTC to\\n/// yield vaults and back. Vaults supply yield strategies with tBTC that\\n/// generate yield for Bitcoin holders.\\ncontract Dispatcher is Router, Ownable2Step {\\n using SafeERC20 for IERC20;\\n\\n /// Struct holds information about a vault.\\n struct VaultInfo {\\n bool authorized;\\n }\\n\\n /// The main stBTC contract holding tBTC deposited by stakers.\\n stBTC public immutable stbtc;\\n /// tBTC token contract.\\n IERC20 public immutable tbtc;\\n /// Address of the maintainer bot.\\n address public maintainer;\\n\\n /// Authorized Yield Vaults that implement ERC4626 standard. These\\n /// vaults deposit assets to yield strategies, e.g. Uniswap V3\\n /// WBTC/TBTC pool. Vault can be a part of Acre ecosystem or can be\\n /// implemented externally. As long as it complies with ERC4626\\n /// standard and is authorized by the owner it can be plugged into\\n /// Acre.\\n address[] public vaults;\\n /// Mapping of vaults to their information.\\n mapping(address => VaultInfo) public vaultsInfo;\\n\\n /// Emitted when a vault is authorized.\\n /// @param vault Address of the vault.\\n event VaultAuthorized(address indexed vault);\\n\\n /// Emitted when a vault is deauthorized.\\n /// @param vault Address of the vault.\\n event VaultDeauthorized(address indexed vault);\\n\\n /// Emitted when tBTC is routed to a vault.\\n /// @param vault Address of the vault.\\n /// @param amount Amount of tBTC.\\n /// @param sharesOut Amount of received shares.\\n event DepositAllocated(\\n address indexed vault,\\n uint256 amount,\\n uint256 sharesOut\\n );\\n\\n /// Emitted when the maintainer address is updated.\\n /// @param maintainer Address of the new maintainer.\\n event MaintainerUpdated(address indexed maintainer);\\n\\n /// Reverts if the vault is already authorized.\\n error VaultAlreadyAuthorized();\\n\\n /// Reverts if the vault is not authorized.\\n error VaultUnauthorized();\\n\\n /// Reverts if the caller is not the maintainer.\\n error NotMaintainer();\\n\\n /// Reverts if the address is zero.\\n error ZeroAddress();\\n\\n /// Modifier that reverts if the caller is not the maintainer.\\n modifier onlyMaintainer() {\\n if (msg.sender != maintainer) {\\n revert NotMaintainer();\\n }\\n _;\\n }\\n\\n constructor(stBTC _stbtc, IERC20 _tbtc) Ownable(msg.sender) {\\n stbtc = _stbtc;\\n tbtc = _tbtc;\\n }\\n\\n /// @notice Adds a vault to the list of authorized vaults.\\n /// @param vault Address of the vault to add.\\n function authorizeVault(address vault) external onlyOwner {\\n if (isVaultAuthorized(vault)) {\\n revert VaultAlreadyAuthorized();\\n }\\n\\n vaults.push(vault);\\n vaultsInfo[vault].authorized = true;\\n\\n emit VaultAuthorized(vault);\\n }\\n\\n /// @notice Removes a vault from the list of authorized vaults.\\n /// @param vault Address of the vault to remove.\\n function deauthorizeVault(address vault) external onlyOwner {\\n if (!isVaultAuthorized(vault)) {\\n revert VaultUnauthorized();\\n }\\n\\n vaultsInfo[vault].authorized = false;\\n\\n for (uint256 i = 0; i < vaults.length; i++) {\\n if (vaults[i] == vault) {\\n vaults[i] = vaults[vaults.length - 1];\\n // slither-disable-next-line costly-loop\\n vaults.pop();\\n break;\\n }\\n }\\n\\n emit VaultDeauthorized(vault);\\n }\\n\\n /// @notice Updates the maintainer address.\\n /// @param newMaintainer Address of the new maintainer.\\n function updateMaintainer(address newMaintainer) external onlyOwner {\\n if (newMaintainer == address(0)) {\\n revert ZeroAddress();\\n }\\n\\n maintainer = newMaintainer;\\n\\n emit MaintainerUpdated(maintainer);\\n }\\n\\n /// TODO: make this function internal once the allocation distribution is\\n /// implemented\\n /// @notice Routes tBTC from stBTC to a vault. Can be called by the maintainer\\n /// only.\\n /// @param vault Address of the vault to route the assets to.\\n /// @param amount Amount of tBTC to deposit.\\n /// @param minSharesOut Minimum amount of shares to receive.\\n function depositToVault(\\n address vault,\\n uint256 amount,\\n uint256 minSharesOut\\n ) public onlyMaintainer {\\n if (!isVaultAuthorized(vault)) {\\n revert VaultUnauthorized();\\n }\\n\\n // slither-disable-next-line arbitrary-send-erc20\\n tbtc.safeTransferFrom(address(stbtc), address(this), amount);\\n tbtc.forceApprove(address(vault), amount);\\n\\n uint256 sharesOut = deposit(\\n IERC4626(vault),\\n address(stbtc),\\n amount,\\n minSharesOut\\n );\\n // slither-disable-next-line reentrancy-events\\n emit DepositAllocated(vault, amount, sharesOut);\\n }\\n\\n /// @notice Returns the list of authorized vaults.\\n function getVaults() public view returns (address[] memory) {\\n return vaults;\\n }\\n\\n /// @notice Returns true if the vault is authorized.\\n /// @param vault Address of the vault to check.\\n function isVaultAuthorized(address vault) public view returns (bool) {\\n return vaultsInfo[vault].authorized;\\n }\\n\\n /// TODO: implement redeem() / withdraw() functions\\n}\\n\",\"keccak256\":\"0x5adb54e73b82adf0befabef894d99d9bb5eb785895851764ec9f497a055ae47f\",\"license\":\"GPL-3.0-only\"},\"contracts/Router.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/interfaces/IERC4626.sol\\\";\\n\\n/// @title Router\\n/// @notice Router is a contract that routes tBTC from stBTC to\\n/// a given vault and back. Vaults supply yield strategies with tBTC that\\n/// generate yield for Bitcoin holders.\\nabstract contract Router {\\n /// Thrown when amount of shares received is below the min set by caller.\\n /// @param vault Address of the vault.\\n /// @param sharesOut Amount of received shares.\\n /// @param minSharesOut Minimum amount of shares expected to receive.\\n error MinSharesError(\\n address vault,\\n uint256 sharesOut,\\n uint256 minSharesOut\\n );\\n\\n /// @notice Routes funds from stBTC to a vault. The amount of tBTC to\\n /// Shares of deposited tBTC are minted to the stBTC contract.\\n /// @param vault Address of the vault to route the funds to.\\n /// @param receiver Address of the receiver of the shares.\\n /// @param amount Amount of tBTC to deposit.\\n /// @param minSharesOut Minimum amount of shares to receive.\\n function deposit(\\n IERC4626 vault,\\n address receiver,\\n uint256 amount,\\n uint256 minSharesOut\\n ) internal returns (uint256 sharesOut) {\\n if ((sharesOut = vault.deposit(amount, receiver)) < minSharesOut) {\\n revert MinSharesError(address(vault), sharesOut, minSharesOut);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x520e27c613f1234755c23402524b048a81abd15222d7f318504992d490248812\",\"license\":\"GPL-3.0-only\"},\"contracts/stBTC.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\\\";\\nimport \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport \\\"@openzeppelin/contracts/access/Ownable2Step.sol\\\";\\nimport \\\"./Dispatcher.sol\\\";\\n\\n/// @title stBTC\\n/// @notice This contract implements the ERC-4626 tokenized vault standard. By\\n/// staking tBTC, users acquire a liquid staking token called stBTC,\\n/// commonly referred to as \\\"shares\\\". The staked tBTC is securely\\n/// deposited into Acre's vaults, where it generates yield over time.\\n/// Users have the flexibility to redeem stBTC, enabling them to\\n/// withdraw their staked tBTC along with the accrued yield.\\n/// @dev ERC-4626 is a standard to optimize and unify the technical parameters\\n/// of yield-bearing vaults. This contract facilitates the minting and\\n/// burning of shares (stBTC), which are represented as standard ERC20\\n/// tokens, providing a seamless exchange with tBTC tokens.\\ncontract stBTC is ERC4626, Ownable2Step {\\n using SafeERC20 for IERC20;\\n\\n /// Dispatcher contract that routes tBTC from stBTC to a given vault and back.\\n Dispatcher public dispatcher;\\n\\n /// Address of the treasury wallet, where fees should be transferred to.\\n address public treasury;\\n\\n /// Minimum amount for a single deposit operation. The value should be set\\n /// low enough so the deposits routed through Bitcoin Depositor contract won't\\n /// be rejected. It means that minimumDepositAmount should be lower than\\n /// tBTC protocol's depositDustThreshold reduced by all the minting fees taken\\n /// before depositing in the Acre contract.\\n uint256 public minimumDepositAmount;\\n\\n /// Maximum total amount of tBTC token held by Acre protocol.\\n uint256 public maximumTotalAssets;\\n\\n /// Emitted when the treasury wallet address is updated.\\n /// @param treasury New treasury wallet address.\\n event TreasuryUpdated(address treasury);\\n\\n /// Emitted when deposit parameters are updated.\\n /// @param minimumDepositAmount New value of the minimum deposit amount.\\n /// @param maximumTotalAssets New value of the maximum total assets amount.\\n event DepositParametersUpdated(\\n uint256 minimumDepositAmount,\\n uint256 maximumTotalAssets\\n );\\n\\n /// Emitted when the dispatcher contract is updated.\\n /// @param oldDispatcher Address of the old dispatcher contract.\\n /// @param newDispatcher Address of the new dispatcher contract.\\n event DispatcherUpdated(address oldDispatcher, address newDispatcher);\\n\\n /// Reverts if the amount is less than the minimum deposit amount.\\n /// @param amount Amount to check.\\n /// @param min Minimum amount to check 'amount' against.\\n error LessThanMinDeposit(uint256 amount, uint256 min);\\n\\n /// Reverts if the address is zero.\\n error ZeroAddress();\\n\\n /// Reverts if the address is disallowed.\\n error DisallowedAddress();\\n\\n constructor(\\n IERC20 _tbtc,\\n address _treasury\\n ) ERC4626(_tbtc) ERC20(\\\"Acre Staked Bitcoin\\\", \\\"stBTC\\\") Ownable(msg.sender) {\\n if (address(_treasury) == address(0)) {\\n revert ZeroAddress();\\n }\\n treasury = _treasury;\\n // TODO: Revisit the exact values closer to the launch.\\n minimumDepositAmount = 0.001 * 1e18; // 0.001 tBTC\\n maximumTotalAssets = 25 * 1e18; // 25 tBTC\\n }\\n\\n /// @notice Updates treasury wallet address.\\n /// @param newTreasury New treasury wallet address.\\n function updateTreasury(address newTreasury) external onlyOwner {\\n // TODO: Introduce a parameters update process.\\n if (newTreasury == address(0)) {\\n revert ZeroAddress();\\n }\\n if (newTreasury == address(this)) {\\n revert DisallowedAddress();\\n }\\n treasury = newTreasury;\\n\\n emit TreasuryUpdated(newTreasury);\\n }\\n\\n /// @notice Updates deposit parameters.\\n /// @dev To disable the limit for deposits, set the maximum total assets to\\n /// maximum (`type(uint256).max`).\\n /// @param _minimumDepositAmount New value of the minimum deposit amount. It\\n /// is the minimum amount for a single deposit operation.\\n /// @param _maximumTotalAssets New value of the maximum total assets amount.\\n /// It is the maximum amount of the tBTC token that the Acre protocol\\n /// can hold.\\n function updateDepositParameters(\\n uint256 _minimumDepositAmount,\\n uint256 _maximumTotalAssets\\n ) external onlyOwner {\\n // TODO: Introduce a parameters update process.\\n minimumDepositAmount = _minimumDepositAmount;\\n maximumTotalAssets = _maximumTotalAssets;\\n\\n emit DepositParametersUpdated(\\n _minimumDepositAmount,\\n _maximumTotalAssets\\n );\\n }\\n\\n // TODO: Implement a governed upgrade process that initiates an update and\\n // then finalizes it after a delay.\\n /// @notice Updates the dispatcher contract and gives it an unlimited\\n /// allowance to transfer staked tBTC.\\n /// @param newDispatcher Address of the new dispatcher contract.\\n function updateDispatcher(Dispatcher newDispatcher) external onlyOwner {\\n if (address(newDispatcher) == address(0)) {\\n revert ZeroAddress();\\n }\\n\\n address oldDispatcher = address(dispatcher);\\n\\n emit DispatcherUpdated(oldDispatcher, address(newDispatcher));\\n dispatcher = newDispatcher;\\n\\n // TODO: Once withdrawal/rebalancing is implemented, we need to revoke the\\n // approval of the vaults share tokens from the old dispatcher and approve\\n // a new dispatcher to manage the share tokens.\\n\\n if (oldDispatcher != address(0)) {\\n // Setting allowance to zero for the old dispatcher\\n IERC20(asset()).forceApprove(oldDispatcher, 0);\\n }\\n\\n // Setting allowance to max for the new dispatcher\\n IERC20(asset()).forceApprove(address(dispatcher), type(uint256).max);\\n }\\n\\n /// @notice Mints shares to receiver by depositing exactly amount of\\n /// tBTC tokens.\\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\\n /// which determines the minimum amount for a single deposit operation.\\n /// The amount of the assets has to be pre-approved in the tBTC\\n /// contract.\\n /// @param assets Approved amount of tBTC tokens to deposit.\\n /// @param receiver The address to which the shares will be minted.\\n /// @return Minted shares.\\n function deposit(\\n uint256 assets,\\n address receiver\\n ) public override returns (uint256) {\\n if (assets < minimumDepositAmount) {\\n revert LessThanMinDeposit(assets, minimumDepositAmount);\\n }\\n\\n return super.deposit(assets, receiver);\\n }\\n\\n /// @notice Mints shares to receiver by depositing tBTC tokens.\\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\\n /// which determines the minimum amount for a single deposit operation.\\n /// The amount of the assets has to be pre-approved in the tBTC\\n /// contract.\\n /// The msg.sender is required to grant approval for tBTC transfer.\\n /// To determine the total assets amount necessary for approval\\n /// corresponding to a given share amount, use the `previewMint` function.\\n /// @param shares Amount of shares to mint.\\n /// @param receiver The address to which the shares will be minted.\\n function mint(\\n uint256 shares,\\n address receiver\\n ) public override returns (uint256 assets) {\\n if ((assets = super.mint(shares, receiver)) < minimumDepositAmount) {\\n revert LessThanMinDeposit(assets, minimumDepositAmount);\\n }\\n }\\n\\n /// @notice Returns value of assets that would be exchanged for the amount of\\n /// shares owned by the `account`.\\n /// @param account Owner of shares.\\n /// @return Assets amount.\\n function assetsBalanceOf(address account) public view returns (uint256) {\\n return convertToAssets(balanceOf(account));\\n }\\n\\n /// @notice Returns the maximum amount of the tBTC token that can be\\n /// deposited into the vault for the receiver through a deposit\\n /// call. It takes into account the deposit parameter, maximum total\\n /// assets, which determines the total amount of tBTC token held by\\n /// Acre protocol.\\n /// @dev When the remaining amount of unused limit is less than the minimum\\n /// deposit amount, this function returns 0.\\n /// @return The maximum amount of tBTC token that can be deposited into\\n /// Acre protocol for the receiver.\\n function maxDeposit(address) public view override returns (uint256) {\\n if (maximumTotalAssets == type(uint256).max) {\\n return type(uint256).max;\\n }\\n\\n uint256 _totalAssets = totalAssets();\\n\\n return\\n _totalAssets >= maximumTotalAssets\\n ? 0\\n : maximumTotalAssets - _totalAssets;\\n }\\n\\n /// @notice Returns the maximum amount of the vault shares that can be\\n /// minted for the receiver, through a mint call.\\n /// @dev Since the stBTC contract limits the maximum total tBTC tokens this\\n /// function converts the maximum deposit amount to shares.\\n /// @return The maximum amount of the vault shares.\\n function maxMint(address receiver) public view override returns (uint256) {\\n uint256 _maxDeposit = maxDeposit(receiver);\\n\\n // slither-disable-next-line incorrect-equality\\n return\\n _maxDeposit == type(uint256).max\\n ? type(uint256).max\\n : convertToShares(_maxDeposit);\\n }\\n\\n /// @return Returns deposit parameters.\\n function depositParameters() public view returns (uint256, uint256) {\\n return (minimumDepositAmount, maximumTotalAssets);\\n }\\n}\\n\",\"keccak256\":\"0x6d980629590d39aa0c1acb2f38c1f100ef08e976cd67ba76c6f99b07ed43865b\",\"license\":\"GPL-3.0-only\"}},\"version\":1}", - "bytecode": "0x60806040523480156200001157600080fd5b506040516200249b3803806200249b8339810160408190526200003491620002f4565b33806200005c57604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b620000678162000106565b5062000074848462000124565b6001600160a01b0382166200009c5760405163182b2a8160e21b815260040160405180910390fd5b6001600160a01b038116620000c45760405163e4ee787760e01b815260040160405180910390fd5b603480546001600160a01b0319166001600160a01b0393841617905560358054919092166001600160e01b031990911617607d60a31b17905550620003519050565b603280546001600160a01b0319169055620001218162000285565b50565b6000546001600160a01b03161580156200014757506001546001600160a01b0316155b620001a75760405162461bcd60e51b815260206004820152602960248201527f4162737472616374544254434465706f7369746f7220616c726561647920696e6044820152681a5d1a585b1a5e995960ba1b606482015260840162000053565b6001600160a01b038216620001ff5760405162461bcd60e51b815260206004820152601d60248201527f42726964676520616464726573732063616e6e6f74206265207a65726f000000604482015260640162000053565b6001600160a01b038116620002575760405162461bcd60e51b815260206004820181905260248201527f544254435661756c7420616464726573732063616e6e6f74206265207a65726f604482015260640162000053565b600080546001600160a01b039384166001600160a01b03199182161790915560018054929093169116179055565b603180546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b80516001600160a01b0381168114620002ef57600080fd5b919050565b600080600080608085870312156200030b57600080fd5b6200031685620002d7565b93506200032660208601620002d7565b92506200033660408601620002d7565b91506200034660608601620002d7565b905092959194509250565b61213a80620003616000396000f3fe608060405234801561001057600080fd5b506004361061016c5760003560e01c8063c143d675116100cd578063da9ad53c11610081578063e5d3d71411610066578063e5d3d71414610355578063e78cea9214610368578063f2fde38b1461037b57600080fd5b8063da9ad53c14610331578063e30c39781461034457600080fd5b8063c9f5a5d8116100b2578063c9f5a5d8146102b4578063d0714ad5146102c7578063d990d3ff1461031e57600080fd5b8063c143d67514610274578063c7ba0347146102a857600080fd5b8063774e2e90116101245780638da5cb5b116101095780638da5cb5b1461023d5780639bef6d521461024e578063b2e665bf1461026157600080fd5b8063774e2e90146101f257806379ba50971461023557600080fd5b80633d11a6ae116101555780633d11a6ae146101b657806369e1df8b146101d7578063715018a6146101ea57600080fd5b80630f36403a146101715780633647b205146101a1575b600080fd5b600154610184906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b6101b46101af366004611977565b61038e565b005b6101c96101c43660046119cb565b61040c565b604051908152602001610198565b6101b46101e5366004611a00565b61047b565b6101b461055a565b610213610200366004611a00565b606081901c9160509190911c61ffff1690565b604080516001600160a01b03909316835261ffff909116602083015201610198565b6101b461056e565b6031546001600160a01b0316610184565b603554610184906001600160a01b031681565b6101b461026f366004611a00565b6105b7565b60355461028f90600160a01b900467ffffffffffffffff1681565b60405167ffffffffffffffff9091168152602001610198565b6101c96402540be40081565b6101b46102c2366004611a00565b610714565b61030f6102d5366004611a00565b60336020526000908152604090205460ff81169061010081046001600160a01b031690600160a81b90046affffffffffffffffffffff1683565b60405161019893929190611a51565b6101b461032c366004611a89565b61084e565b6101b461033f366004611a00565b6108f2565b6032546001600160a01b0316610184565b603454610184906001600160a01b031681565b600054610184906001600160a01b031681565b6101b4610389366004611b0d565b6109a9565b610396610a27565b603580547fffffffff0000000000000000ffffffffffffffffffffffffffffffffffffffff16600160a01b67ffffffffffffffff8416908102919091179091556040519081527f53a618edd6eab9ce346f438670ebd45da60fa3d85662375fae2b8beadf08faf39060200160405180910390a150565b6040516bffffffffffffffffffffffff19606084901b1660208201527fffff00000000000000000000000000000000000000000000000000000000000060f083901b16603482015260009060360160405160208183030381529060405261047290611b2a565b90505b92915050565b6104888160016003610a54565b6000818152603360205260408120906104a083610b0b565b83546001600160a01b03909116610100027fffffffffffffffffffffff0000000000000000000000000000000000000000ff90911617835590506104e381610dd7565b825474ffffffffffffffffffffffffffffffffffffffffff16600160a81b6affffffffffffffffffffff9283168102919091178085556040519190049091168152339084907ff412c1941036889a8a2aec22dca20565f685239ac78976dab58b52eb70f972fa9060200160405180910390a3505050565b610562610a27565b61056c6000610e2c565b565b60325433906001600160a01b031681146105ab5760405163118cdaa760e01b81526001600160a01b03821660048201526024015b60405180910390fd5b6105b481610e2c565b50565b6105c48160036004610a54565b600081815260336020526040812080549091600160a81b9091046affffffffffffffffffffff16900361060a57604051632145277d60e21b815260040160405180910390fd5b805474ffffffffffffffffffffffffffffffffffffffffff81168255604051600160a81b9091046affffffffffffffffffffff1680825290339084907ff0a477d0ba7b549d19236a4c6517edef5574c03ed185bad57c92c9323091af8f9060200160405180910390a3603554603454610690916001600160a01b03918216911683610e52565b6035548254604051636e553f6560e01b8152600481018490526001600160a01b0361010090920482166024820152911690636e553f65906044015b6020604051808303816000875af11580156106ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061070e9190611b51565b50505050565b6107218160036005610a54565b600081815260336020526040812080549091600160a81b9091046affffffffffffffffffffff16900361076757604051632145277d60e21b815260040160405180910390fd5b805461010090046001600160a01b031633146107af576040517f709d46f200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b805474ffffffffffffffffffffffffffffffffffffffffff8116808355604051600160a81b9092046affffffffffffffffffffff16808352916101009091046001600160a01b03169084907f32aa57d54fb0ee2c9617ac9d5982ba7d88869fcbf89542a285d6c07b03dc504e9060200160405180910390a38154603454610849916001600160a01b03918216916101009091041683610ef5565b505050565b6001600160a01b03821661088e576040517ff606bf2a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006108a4858561089f868661040c565b610f69565b90506108b38160006001610a54565b6040516001600160a01b03841690339083907f8d019883471b734b0033fe25a5b76c3afefbbfa9e9b3dacdbabf505b9e4f455d90600090a45050505050565b6108ff8160016002610a54565b60008061090b83610b0b565b91509150336001600160a01b0316837f2b57d79a66895fd41ae6d27049952259b0d40a9b7c563a99b3f1844b288da08c8460405161094b91815260200190565b60405180910390a3603554603454610970916001600160a01b03918216911684610e52565b603554604051636e553f6560e01b8152600481018490526001600160a01b03838116602483015290911690636e553f65906044016106cb565b6109b1610a27565b603280546001600160a01b03831673ffffffffffffffffffffffffffffffffffffffff1990911681179091556109ef6031546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b6031546001600160a01b0316331461056c5760405163118cdaa760e01b81523360048201526024016105a2565b816005811115610a6657610a66611a19565b60008481526033602052604090205460ff166005811115610a8957610a89611a19565b14610ad657600083815260336020526040908190205490517fbcbf502b0000000000000000000000000000000000000000000000000000000081526105a29160ff16908490600401611b6a565b6000838152603360205260409020805482919060ff19166001836005811115610b0157610b01611a19565b0217905550505050565b6000806000806000610b1c866110c6565b6034546040516370a0823160e01b815230600482015293965091945092506000916001600160a01b03909116906370a0823190602401602060405180830381865afa158015610b6f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b939190611b51565b6034546040516370a0823160e01b81523060048201529192506001600160a01b0316906370a0823190602401602060405180830381865afa158015610bdc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c009190611b51565b831115610c43576040517fcad48b6900000000000000000000000000000000000000000000000000000000815260048101849052602481018290526044016105a2565b603554600090600160a01b900467ffffffffffffffff16610c65576000610c83565b603554610c8390600160a01b900467ffffffffffffffff1686611b9b565b9050838110610cc8576040517f2395edf200000000000000000000000000000000000000000000000000000000815260048101829052602481018590526044016105a2565b6000610cd48286611bbd565b6040805187815260208101859052919250606086901c9161ffff605088901c1691829133918e917f6410e64d304208a5e90fc76ab4fbf4e7b8836705daeda8dde27611ae0524490a910160405180910390a48315610dc757603554604080517f61d027b30000000000000000000000000000000000000000000000000000000081529051610dc7926001600160a01b0316916361d027b39160048083019260209291908290030181865afa158015610d90573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610db49190611bdb565b6034546001600160a01b03169086610ef5565b5090999098509650505050505050565b60006affffffffffffffffffffff821115610e28576040517f6dfcc65000000000000000000000000000000000000000000000000000000000815260586004820152602481018390526044016105a2565b5090565b6032805473ffffffffffffffffffffffffffffffffffffffff191690556105b481611350565b6040517fdd62ed3e0000000000000000000000000000000000000000000000000000000081523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015610ebb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610edf9190611b51565b905061070e8484610ef08585611bf8565b6113af565b6040516001600160a01b0383811660248301526044820183905261084991859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050611469565b6001546000906001600160a01b0316610f8860c0850160a08601611b0d565b6001600160a01b031614610fde5760405162461bcd60e51b815260206004820152601660248201527f5661756c742061646472657373206d69736d617463680000000000000000000060448201526064016105a2565b6000610ffe610fec866114e5565b610ff96020870187611c1d565b61154a565b60405163ffffffff4216815290915081907fa3ed7aef0745e1a91addae9e5daee7a8ace74852fec840b9d93da747855dd7b99060200160405180910390a26000546040517f86f014390000000000000000000000000000000000000000000000000000000081526001600160a01b03909116906386f014399061108990889088908890600401611ce5565b600060405180830381600087803b1580156110a357600080fd5b505af11580156110b7573d6000803e3d6000fd5b509293505050505b9392505050565b600080546040517fb02c43d0000000000000000000000000000000000000000000000000000000008152600481018490528291829182916001600160a01b03169063b02c43d09060240160e060405180830381865afa15801561112d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111519190611e60565b9050806040015163ffffffff166000036111ad5760405162461bcd60e51b815260206004820152601760248201527f4465706f736974206e6f7420696e697469616c697a656400000000000000000060448201526064016105a2565b6001546040517f6c626aa4000000000000000000000000000000000000000000000000000000008152600481018790526000916001600160a01b031690636c626aa49060240160408051808303816000875af1158015611211573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112359190611f1a565b9150508160a0015163ffffffff16600014158061125b575067ffffffffffffffff811615155b6112cd5760405162461bcd60e51b815260206004820152602360248201527f4465706f736974206e6f742066696e616c697a6564206279207468652062726960448201527f646765000000000000000000000000000000000000000000000000000000000060648201526084016105a2565b6402540be400826020015167ffffffffffffffff166112ec9190611f54565b945061130082602001518360800151611594565b6040805182815263ffffffff4216602082015291955087917f417b6288c9f637614f8b3f7a275fb4e44e517930fde949e463d58dfe0b97f28b910160405180910390a25060c00151929491935050565b603180546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f095ea7b30000000000000000000000000000000000000000000000000000000017905261142e8482611717565b61070e576040516001600160a01b0384811660248301526000604483015261146391869182169063095ea7b390606401610f22565b61070e84825b600061147e6001600160a01b038416836117bf565b905080516000141580156114a35750808060200190518101906114a19190611f6b565b155b15610849576040517f5274afe70000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024016105a2565b60006104756114f76020840184611f8d565b6115046020850185611fa8565b6115116040870187611fa8565b6115216080890160608a01611f8d565b60405160200161153696959493929190611fef565b6040516020818303038152906040526117cd565b6000828260405160200161157592919091825260e01b6001600160e01b031916602082015260240190565b60408051601f1981840301815291905280516020909101209392505050565b6000806402540be4006115a78486612031565b67ffffffffffffffff166115bb9190611f54565b90506000600160009054906101000a90046001600160a01b03166001600160a01b03166309b53f516040518163ffffffff1660e01b8152600401602060405180830381865afa158015611612573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116369190612059565b63ffffffff169050600080821161164e576000611658565b6116588284611b9b565b905060008060009054906101000a90046001600160a01b03166001600160a01b031663c42b64d06040518163ffffffff1660e01b8152600401608060405180830381865afa1580156116ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116d29190612076565b509250505060006402540be4008267ffffffffffffffff166116f49190611f54565b9050806117018487611bbd565b61170b9190611bbd565b98975050505050505050565b6000806000846001600160a01b03168460405161173491906120d5565b6000604051808303816000865af19150503d8060008114611771576040519150601f19603f3d011682016040523d82523d6000602084013e611776565b606091505b50915091508180156117a05750805115806117a05750808060200190518101906117a09190611f6b565b80156117b657506000856001600160a01b03163b115b95945050505050565b6060610472838360006117f4565b60006020600083516020850160025afa50602060006020600060025afa5050600051919050565b606081471015611832576040517fcd7860590000000000000000000000000000000000000000000000000000000081523060048201526024016105a2565b600080856001600160a01b0316848660405161184e91906120d5565b60006040518083038185875af1925050503d806000811461188b576040519150601f19603f3d011682016040523d82523d6000602084013e611890565b606091505b50915091506118a08683836118aa565b9695505050505050565b6060826118bf576118ba8261191f565b6110bf565b81511580156118d657506001600160a01b0384163b155b15611918576040517f9996b3150000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024016105a2565b50806110bf565b80511561192f5780518082602001fd5b6040517f1425ea4200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b67ffffffffffffffff811681146105b457600080fd5b60006020828403121561198957600080fd5b81356110bf81611961565b6001600160a01b03811681146105b457600080fd5b80356119b481611994565b919050565b803561ffff811681146119b457600080fd5b600080604083850312156119de57600080fd5b82356119e981611994565b91506119f7602084016119b9565b90509250929050565b600060208284031215611a1257600080fd5b5035919050565b634e487b7160e01b600052602160045260246000fd5b60068110611a4d57634e487b7160e01b600052602160045260246000fd5b9052565b60608101611a5f8286611a2f565b6001600160a01b03841660208301526affffffffffffffffffffff83166040830152949350505050565b600080600080848603610120811215611aa157600080fd5b853567ffffffffffffffff811115611ab857600080fd5b860160808189031215611aca57600080fd5b945060c0601f1982011215611ade57600080fd5b5060208501925060e0850135611af381611994565b9150611b0261010086016119b9565b905092959194509250565b600060208284031215611b1f57600080fd5b81356110bf81611994565b80516020808301519190811015611b4b576000198160200360031b1b821691505b50919050565b600060208284031215611b6357600080fd5b5051919050565b60408101611b788285611a2f565b6110bf6020830184611a2f565b634e487b7160e01b600052601160045260246000fd5b600082611bb857634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561047557610475611b85565b80516119b481611994565b600060208284031215611bed57600080fd5b81516110bf81611994565b8082018082111561047557610475611b85565b63ffffffff811681146105b457600080fd5b600060208284031215611c2f57600080fd5b81356110bf81611c0b565b80356001600160e01b0319811681146119b457600080fd5b6000808335601e19843603018112611c6957600080fd5b830160208101925035905067ffffffffffffffff811115611c8957600080fd5b803603821315611c9857600080fd5b9250929050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b80356bffffffffffffffffffffffff19811681146119b457600080fd5b60006101008083526001600160e01b031980611d0088611c3a565b1682850152611d126020880188611c52565b92506080610120860152611d2b61018086018483611c9f565b925050611d3b6040880188611c52565b85840360ff1901610140870152611d53848284611c9f565b9350505080611d6460608901611c3a565b166101608501525090508335611d7981611c0b565b63ffffffff811660208401525060208401357fffffffffffffffff0000000000000000000000000000000000000000000000008116808214611dba57600080fd5b80604085015250506bffffffffffffffffffffffff19611ddc60408601611cc8565b166060830152611dee60608501611cc8565b6bffffffffffffffffffffffff198116608084015250611e1060808501611c3a565b6001600160e01b0319811660a084015250611e2d60a085016119a9565b6001600160a01b031660c083015260e09091019190915292915050565b80516119b481611961565b80516119b481611c0b565b600060e08284031215611e7257600080fd5b60405160e0810181811067ffffffffffffffff82111715611ea357634e487b7160e01b600052604160045260246000fd5b604052611eaf83611bd0565b8152611ebd60208401611e4a565b6020820152611ece60408401611e55565b6040820152611edf60608401611bd0565b6060820152611ef060808401611e4a565b6080820152611f0160a08401611e55565b60a082015260c083015160c08201528091505092915050565b60008060408385031215611f2d57600080fd5b8251611f3881611961565b6020840151909250611f4981611961565b809150509250929050565b808202811582820484141761047557610475611b85565b600060208284031215611f7d57600080fd5b815180151581146110bf57600080fd5b600060208284031215611f9f57600080fd5b61047282611c3a565b6000808335601e19843603018112611fbf57600080fd5b83018035915067ffffffffffffffff821115611fda57600080fd5b602001915036819003821315611c9857600080fd5b60006001600160e01b03198089168352868860048501378683016004810160008152868882375093169390920160048101939093525050600801949350505050565b67ffffffffffffffff82811682821603908082111561205257612052611b85565b5092915050565b60006020828403121561206b57600080fd5b81516110bf81611c0b565b6000806000806080858703121561208c57600080fd5b845161209781611961565b60208601519094506120a881611961565b60408601519093506120b981611961565b60608601519092506120ca81611c0b565b939692955090935050565b6000825160005b818110156120f657602081860181015185830152016120dc565b50600092019182525091905056fea2646970667358221220462bf22e2a3e5c424c7897cc702ca2994745ded2b209ca480d6b59b6977ef88a64736f6c63430008150033", - "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061016c5760003560e01c8063c143d675116100cd578063da9ad53c11610081578063e5d3d71411610066578063e5d3d71414610355578063e78cea9214610368578063f2fde38b1461037b57600080fd5b8063da9ad53c14610331578063e30c39781461034457600080fd5b8063c9f5a5d8116100b2578063c9f5a5d8146102b4578063d0714ad5146102c7578063d990d3ff1461031e57600080fd5b8063c143d67514610274578063c7ba0347146102a857600080fd5b8063774e2e90116101245780638da5cb5b116101095780638da5cb5b1461023d5780639bef6d521461024e578063b2e665bf1461026157600080fd5b8063774e2e90146101f257806379ba50971461023557600080fd5b80633d11a6ae116101555780633d11a6ae146101b657806369e1df8b146101d7578063715018a6146101ea57600080fd5b80630f36403a146101715780633647b205146101a1575b600080fd5b600154610184906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b6101b46101af366004611977565b61038e565b005b6101c96101c43660046119cb565b61040c565b604051908152602001610198565b6101b46101e5366004611a00565b61047b565b6101b461055a565b610213610200366004611a00565b606081901c9160509190911c61ffff1690565b604080516001600160a01b03909316835261ffff909116602083015201610198565b6101b461056e565b6031546001600160a01b0316610184565b603554610184906001600160a01b031681565b6101b461026f366004611a00565b6105b7565b60355461028f90600160a01b900467ffffffffffffffff1681565b60405167ffffffffffffffff9091168152602001610198565b6101c96402540be40081565b6101b46102c2366004611a00565b610714565b61030f6102d5366004611a00565b60336020526000908152604090205460ff81169061010081046001600160a01b031690600160a81b90046affffffffffffffffffffff1683565b60405161019893929190611a51565b6101b461032c366004611a89565b61084e565b6101b461033f366004611a00565b6108f2565b6032546001600160a01b0316610184565b603454610184906001600160a01b031681565b600054610184906001600160a01b031681565b6101b4610389366004611b0d565b6109a9565b610396610a27565b603580547fffffffff0000000000000000ffffffffffffffffffffffffffffffffffffffff16600160a01b67ffffffffffffffff8416908102919091179091556040519081527f53a618edd6eab9ce346f438670ebd45da60fa3d85662375fae2b8beadf08faf39060200160405180910390a150565b6040516bffffffffffffffffffffffff19606084901b1660208201527fffff00000000000000000000000000000000000000000000000000000000000060f083901b16603482015260009060360160405160208183030381529060405261047290611b2a565b90505b92915050565b6104888160016003610a54565b6000818152603360205260408120906104a083610b0b565b83546001600160a01b03909116610100027fffffffffffffffffffffff0000000000000000000000000000000000000000ff90911617835590506104e381610dd7565b825474ffffffffffffffffffffffffffffffffffffffffff16600160a81b6affffffffffffffffffffff9283168102919091178085556040519190049091168152339084907ff412c1941036889a8a2aec22dca20565f685239ac78976dab58b52eb70f972fa9060200160405180910390a3505050565b610562610a27565b61056c6000610e2c565b565b60325433906001600160a01b031681146105ab5760405163118cdaa760e01b81526001600160a01b03821660048201526024015b60405180910390fd5b6105b481610e2c565b50565b6105c48160036004610a54565b600081815260336020526040812080549091600160a81b9091046affffffffffffffffffffff16900361060a57604051632145277d60e21b815260040160405180910390fd5b805474ffffffffffffffffffffffffffffffffffffffffff81168255604051600160a81b9091046affffffffffffffffffffff1680825290339084907ff0a477d0ba7b549d19236a4c6517edef5574c03ed185bad57c92c9323091af8f9060200160405180910390a3603554603454610690916001600160a01b03918216911683610e52565b6035548254604051636e553f6560e01b8152600481018490526001600160a01b0361010090920482166024820152911690636e553f65906044015b6020604051808303816000875af11580156106ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061070e9190611b51565b50505050565b6107218160036005610a54565b600081815260336020526040812080549091600160a81b9091046affffffffffffffffffffff16900361076757604051632145277d60e21b815260040160405180910390fd5b805461010090046001600160a01b031633146107af576040517f709d46f200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b805474ffffffffffffffffffffffffffffffffffffffffff8116808355604051600160a81b9092046affffffffffffffffffffff16808352916101009091046001600160a01b03169084907f32aa57d54fb0ee2c9617ac9d5982ba7d88869fcbf89542a285d6c07b03dc504e9060200160405180910390a38154603454610849916001600160a01b03918216916101009091041683610ef5565b505050565b6001600160a01b03821661088e576040517ff606bf2a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006108a4858561089f868661040c565b610f69565b90506108b38160006001610a54565b6040516001600160a01b03841690339083907f8d019883471b734b0033fe25a5b76c3afefbbfa9e9b3dacdbabf505b9e4f455d90600090a45050505050565b6108ff8160016002610a54565b60008061090b83610b0b565b91509150336001600160a01b0316837f2b57d79a66895fd41ae6d27049952259b0d40a9b7c563a99b3f1844b288da08c8460405161094b91815260200190565b60405180910390a3603554603454610970916001600160a01b03918216911684610e52565b603554604051636e553f6560e01b8152600481018490526001600160a01b03838116602483015290911690636e553f65906044016106cb565b6109b1610a27565b603280546001600160a01b03831673ffffffffffffffffffffffffffffffffffffffff1990911681179091556109ef6031546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b6031546001600160a01b0316331461056c5760405163118cdaa760e01b81523360048201526024016105a2565b816005811115610a6657610a66611a19565b60008481526033602052604090205460ff166005811115610a8957610a89611a19565b14610ad657600083815260336020526040908190205490517fbcbf502b0000000000000000000000000000000000000000000000000000000081526105a29160ff16908490600401611b6a565b6000838152603360205260409020805482919060ff19166001836005811115610b0157610b01611a19565b0217905550505050565b6000806000806000610b1c866110c6565b6034546040516370a0823160e01b815230600482015293965091945092506000916001600160a01b03909116906370a0823190602401602060405180830381865afa158015610b6f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b939190611b51565b6034546040516370a0823160e01b81523060048201529192506001600160a01b0316906370a0823190602401602060405180830381865afa158015610bdc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c009190611b51565b831115610c43576040517fcad48b6900000000000000000000000000000000000000000000000000000000815260048101849052602481018290526044016105a2565b603554600090600160a01b900467ffffffffffffffff16610c65576000610c83565b603554610c8390600160a01b900467ffffffffffffffff1686611b9b565b9050838110610cc8576040517f2395edf200000000000000000000000000000000000000000000000000000000815260048101829052602481018590526044016105a2565b6000610cd48286611bbd565b6040805187815260208101859052919250606086901c9161ffff605088901c1691829133918e917f6410e64d304208a5e90fc76ab4fbf4e7b8836705daeda8dde27611ae0524490a910160405180910390a48315610dc757603554604080517f61d027b30000000000000000000000000000000000000000000000000000000081529051610dc7926001600160a01b0316916361d027b39160048083019260209291908290030181865afa158015610d90573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610db49190611bdb565b6034546001600160a01b03169086610ef5565b5090999098509650505050505050565b60006affffffffffffffffffffff821115610e28576040517f6dfcc65000000000000000000000000000000000000000000000000000000000815260586004820152602481018390526044016105a2565b5090565b6032805473ffffffffffffffffffffffffffffffffffffffff191690556105b481611350565b6040517fdd62ed3e0000000000000000000000000000000000000000000000000000000081523060048201526001600160a01b0383811660248301526000919085169063dd62ed3e90604401602060405180830381865afa158015610ebb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610edf9190611b51565b905061070e8484610ef08585611bf8565b6113af565b6040516001600160a01b0383811660248301526044820183905261084991859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050611469565b6001546000906001600160a01b0316610f8860c0850160a08601611b0d565b6001600160a01b031614610fde5760405162461bcd60e51b815260206004820152601660248201527f5661756c742061646472657373206d69736d617463680000000000000000000060448201526064016105a2565b6000610ffe610fec866114e5565b610ff96020870187611c1d565b61154a565b60405163ffffffff4216815290915081907fa3ed7aef0745e1a91addae9e5daee7a8ace74852fec840b9d93da747855dd7b99060200160405180910390a26000546040517f86f014390000000000000000000000000000000000000000000000000000000081526001600160a01b03909116906386f014399061108990889088908890600401611ce5565b600060405180830381600087803b1580156110a357600080fd5b505af11580156110b7573d6000803e3d6000fd5b509293505050505b9392505050565b600080546040517fb02c43d0000000000000000000000000000000000000000000000000000000008152600481018490528291829182916001600160a01b03169063b02c43d09060240160e060405180830381865afa15801561112d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111519190611e60565b9050806040015163ffffffff166000036111ad5760405162461bcd60e51b815260206004820152601760248201527f4465706f736974206e6f7420696e697469616c697a656400000000000000000060448201526064016105a2565b6001546040517f6c626aa4000000000000000000000000000000000000000000000000000000008152600481018790526000916001600160a01b031690636c626aa49060240160408051808303816000875af1158015611211573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112359190611f1a565b9150508160a0015163ffffffff16600014158061125b575067ffffffffffffffff811615155b6112cd5760405162461bcd60e51b815260206004820152602360248201527f4465706f736974206e6f742066696e616c697a6564206279207468652062726960448201527f646765000000000000000000000000000000000000000000000000000000000060648201526084016105a2565b6402540be400826020015167ffffffffffffffff166112ec9190611f54565b945061130082602001518360800151611594565b6040805182815263ffffffff4216602082015291955087917f417b6288c9f637614f8b3f7a275fb4e44e517930fde949e463d58dfe0b97f28b910160405180910390a25060c00151929491935050565b603180546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f095ea7b30000000000000000000000000000000000000000000000000000000017905261142e8482611717565b61070e576040516001600160a01b0384811660248301526000604483015261146391869182169063095ea7b390606401610f22565b61070e84825b600061147e6001600160a01b038416836117bf565b905080516000141580156114a35750808060200190518101906114a19190611f6b565b155b15610849576040517f5274afe70000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024016105a2565b60006104756114f76020840184611f8d565b6115046020850185611fa8565b6115116040870187611fa8565b6115216080890160608a01611f8d565b60405160200161153696959493929190611fef565b6040516020818303038152906040526117cd565b6000828260405160200161157592919091825260e01b6001600160e01b031916602082015260240190565b60408051601f1981840301815291905280516020909101209392505050565b6000806402540be4006115a78486612031565b67ffffffffffffffff166115bb9190611f54565b90506000600160009054906101000a90046001600160a01b03166001600160a01b03166309b53f516040518163ffffffff1660e01b8152600401602060405180830381865afa158015611612573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116369190612059565b63ffffffff169050600080821161164e576000611658565b6116588284611b9b565b905060008060009054906101000a90046001600160a01b03166001600160a01b031663c42b64d06040518163ffffffff1660e01b8152600401608060405180830381865afa1580156116ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116d29190612076565b509250505060006402540be4008267ffffffffffffffff166116f49190611f54565b9050806117018487611bbd565b61170b9190611bbd565b98975050505050505050565b6000806000846001600160a01b03168460405161173491906120d5565b6000604051808303816000865af19150503d8060008114611771576040519150601f19603f3d011682016040523d82523d6000602084013e611776565b606091505b50915091508180156117a05750805115806117a05750808060200190518101906117a09190611f6b565b80156117b657506000856001600160a01b03163b115b95945050505050565b6060610472838360006117f4565b60006020600083516020850160025afa50602060006020600060025afa5050600051919050565b606081471015611832576040517fcd7860590000000000000000000000000000000000000000000000000000000081523060048201526024016105a2565b600080856001600160a01b0316848660405161184e91906120d5565b60006040518083038185875af1925050503d806000811461188b576040519150601f19603f3d011682016040523d82523d6000602084013e611890565b606091505b50915091506118a08683836118aa565b9695505050505050565b6060826118bf576118ba8261191f565b6110bf565b81511580156118d657506001600160a01b0384163b155b15611918576040517f9996b3150000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024016105a2565b50806110bf565b80511561192f5780518082602001fd5b6040517f1425ea4200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b67ffffffffffffffff811681146105b457600080fd5b60006020828403121561198957600080fd5b81356110bf81611961565b6001600160a01b03811681146105b457600080fd5b80356119b481611994565b919050565b803561ffff811681146119b457600080fd5b600080604083850312156119de57600080fd5b82356119e981611994565b91506119f7602084016119b9565b90509250929050565b600060208284031215611a1257600080fd5b5035919050565b634e487b7160e01b600052602160045260246000fd5b60068110611a4d57634e487b7160e01b600052602160045260246000fd5b9052565b60608101611a5f8286611a2f565b6001600160a01b03841660208301526affffffffffffffffffffff83166040830152949350505050565b600080600080848603610120811215611aa157600080fd5b853567ffffffffffffffff811115611ab857600080fd5b860160808189031215611aca57600080fd5b945060c0601f1982011215611ade57600080fd5b5060208501925060e0850135611af381611994565b9150611b0261010086016119b9565b905092959194509250565b600060208284031215611b1f57600080fd5b81356110bf81611994565b80516020808301519190811015611b4b576000198160200360031b1b821691505b50919050565b600060208284031215611b6357600080fd5b5051919050565b60408101611b788285611a2f565b6110bf6020830184611a2f565b634e487b7160e01b600052601160045260246000fd5b600082611bb857634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561047557610475611b85565b80516119b481611994565b600060208284031215611bed57600080fd5b81516110bf81611994565b8082018082111561047557610475611b85565b63ffffffff811681146105b457600080fd5b600060208284031215611c2f57600080fd5b81356110bf81611c0b565b80356001600160e01b0319811681146119b457600080fd5b6000808335601e19843603018112611c6957600080fd5b830160208101925035905067ffffffffffffffff811115611c8957600080fd5b803603821315611c9857600080fd5b9250929050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b80356bffffffffffffffffffffffff19811681146119b457600080fd5b60006101008083526001600160e01b031980611d0088611c3a565b1682850152611d126020880188611c52565b92506080610120860152611d2b61018086018483611c9f565b925050611d3b6040880188611c52565b85840360ff1901610140870152611d53848284611c9f565b9350505080611d6460608901611c3a565b166101608501525090508335611d7981611c0b565b63ffffffff811660208401525060208401357fffffffffffffffff0000000000000000000000000000000000000000000000008116808214611dba57600080fd5b80604085015250506bffffffffffffffffffffffff19611ddc60408601611cc8565b166060830152611dee60608501611cc8565b6bffffffffffffffffffffffff198116608084015250611e1060808501611c3a565b6001600160e01b0319811660a084015250611e2d60a085016119a9565b6001600160a01b031660c083015260e09091019190915292915050565b80516119b481611961565b80516119b481611c0b565b600060e08284031215611e7257600080fd5b60405160e0810181811067ffffffffffffffff82111715611ea357634e487b7160e01b600052604160045260246000fd5b604052611eaf83611bd0565b8152611ebd60208401611e4a565b6020820152611ece60408401611e55565b6040820152611edf60608401611bd0565b6060820152611ef060808401611e4a565b6080820152611f0160a08401611e55565b60a082015260c083015160c08201528091505092915050565b60008060408385031215611f2d57600080fd5b8251611f3881611961565b6020840151909250611f4981611961565b809150509250929050565b808202811582820484141761047557610475611b85565b600060208284031215611f7d57600080fd5b815180151581146110bf57600080fd5b600060208284031215611f9f57600080fd5b61047282611c3a565b6000808335601e19843603018112611fbf57600080fd5b83018035915067ffffffffffffffff821115611fda57600080fd5b602001915036819003821315611c9857600080fd5b60006001600160e01b03198089168352868860048501378683016004810160008152868882375093169390920160048101939093525050600801949350505050565b67ffffffffffffffff82811682821603908082111561205257612052611b85565b5092915050565b60006020828403121561206b57600080fd5b81516110bf81611c0b565b6000806000806080858703121561208c57600080fd5b845161209781611961565b60208601519094506120a881611961565b60408601519093506120b981611961565b60608601519092506120ca81611c0b565b939692955090935050565b6000825160005b818110156120f657602081860181015185830152016120dc565b50600092019182525091905056fea2646970667358221220462bf22e2a3e5c424c7897cc702ca2994745ded2b209ca480d6b59b6977ef88a64736f6c63430008150033", - "devdoc": { - "errors": { - "AddressEmptyCode(address)": [ - { - "details": "There's no code at `target` (it is not a contract)." - } - ], - "AddressInsufficientBalance(address)": [ - { - "details": "The ETH balance of the account is not enough to perform the operation." - } - ], - "BridgingCompletionAlreadyNotified()": [ - { - "details": "Attempted to notify a bridging completion, while it was already notified." - } - ], - "BridgingFinalizationAlreadyCalled()": [ - { - "details": "Attempted to call bridging finalization for a stake request for which the function was already called." - } - ], - "BridgingNotCompleted()": [ - { - "details": "Attempted to finalize a stake request, while bridging completion has not been notified yet." - } - ], - "CallerNotStaker()": [ - { - "details": "Attempted to call function by an account that is not the staker." - } - ], - "DepositorFeeExceedsBridgedAmount(uint256,uint256)": [ - { - "details": "Calculated depositor fee exceeds the amount of minted tBTC tokens." - } - ], - "FailedInnerCall()": [ - { - "details": "A call to an address target failed. The target may have reverted." - } - ], - "InsufficientTbtcBalance(uint256,uint256)": [ - { - "details": "Attempted to finalize bridging with depositor's contract tBTC balance lower than the calculated bridged tBTC amount. This error means that Governance should top-up the tBTC reserve for bridging fees approximation." - } - ], - "OwnableInvalidOwner(address)": [ - { - "details": "The owner is not a valid owner account. (eg. `address(0)`)" - } - ], - "OwnableUnauthorizedAccount(address)": [ - { - "details": "The caller account is not authorized to perform an operation." - } - ], - "SafeCastOverflowedUintDowncast(uint8,uint256)": [ - { - "details": "Value doesn't fit in an uint of `bits` size." - } - ], - "SafeERC20FailedOperation(address)": [ - { - "details": "An operation with an ERC20 token failed." - } - ], - "StakeRequestNotQueued()": [ - { - "details": "Attempted to finalize or cancel a stake request that was not added to the queue, or was already finalized or cancelled." - } - ], - "StakerIsZeroAddress()": [ - { - "details": "Staker address is zero." - } - ], - "UnexpectedStakeRequestState(uint8,uint8)": [ - { - "details": "Attempted to execute function for stake request in unexpected current state." - } - ] - }, - "events": { - "BridgingCompleted(uint256,address,uint16,uint256,uint256)": { - "params": { - "bridgedAmount": "Amount of tBTC tokens that was bridged by the tBTC bridge.", - "caller": "Address that notified about bridging completion.", - "depositKey": "Deposit key identifying the deposit.", - "depositorFee": "Depositor fee amount.", - "referral": "Identifier of a partner in the referral program." - } - }, - "DepositorFeeDivisorUpdated(uint64)": { - "params": { - "depositorFeeDivisor": "New value of the depositor fee divisor." - } - }, - "StakeRequestCancelledFromQueue(uint256,address,uint256)": { - "params": { - "amountToStake": "Amount of queued tBTC tokens that got cancelled.", - "depositKey": "Deposit key identifying the deposit.", - "staker": "Address of the staker." - } - }, - "StakeRequestFinalized(uint256,address,uint256)": { - "details": "Deposit details can be fetched from {{ ERC4626.Deposit }} event emitted in the same transaction.", - "params": { - "caller": "Address that finalized the stake request.", - "depositKey": "Deposit key identifying the deposit.", - "stakedAmount": "Amount of staked tBTC tokens." - } - }, - "StakeRequestFinalizedFromQueue(uint256,address,uint256)": { - "details": "Deposit details can be fetched from {{ ERC4626.Deposit }} event emitted in the same transaction.", - "params": { - "caller": "Address that finalized the stake request.", - "depositKey": "Deposit key identifying the deposit.", - "stakedAmount": "Amount of staked tBTC tokens." - } - }, - "StakeRequestInitialized(uint256,address,address)": { - "details": "Deposit details can be fetched from {{ Bridge.DepositRevealed }} event emitted in the same transaction.", - "params": { - "caller": "Address that initialized the stake request.", - "depositKey": "Deposit key identifying the deposit.", - "staker": "The address to which the stBTC shares will be minted." - } - }, - "StakeRequestQueued(uint256,address,uint256)": { - "params": { - "caller": "Address that finalized the stake request.", - "depositKey": "Deposit key identifying the deposit.", - "queuedAmount": "Amount of queued tBTC tokens." - } - } - }, - "kind": "dev", - "methods": { - "acceptOwnership()": { - "details": "The new owner accepts the ownership transfer." - }, - "cancelQueuedStake(uint256)": { - "details": "This function can be called only after the stake request was added to queue.Only staker provided in the extra data of the stake request can call this function.", - "params": { - "depositKey": "Deposit key identifying the deposit." - } - }, - "constructor": { - "params": { - "_stbtc": "stBTC contract instance.", - "_tbtcToken": "tBTC token contract instance.", - "bridge": "tBTC Bridge contract instance.", - "tbtcVault": "tBTC Vault contract instance." - } - }, - "decodeExtraData(bytes32)": { - "details": "Unpacks the data from bytes32: 20 bytes of staker address and 2 bytes of referral, 10 bytes of trailing zeros.", - "params": { - "extraData": "Encoded extra data." - }, - "returns": { - "referral": "Data used for referral program.", - "staker": "The address to which the stBTC shares will be minted." - } - }, - "encodeExtraData(address,uint16)": { - "details": "Packs the data to bytes32: 20 bytes of staker address and 2 bytes of referral, 10 bytes of trailing zeros.", - "params": { - "referral": "Data used for referral program.", - "staker": "The address to which the stBTC shares will be minted." - }, - "returns": { - "_0": "Encoded extra data." - } - }, - "finalizeQueuedStake(uint256)": { - "params": { - "depositKey": "Deposit key identifying the deposit." - } - }, - "finalizeStake(uint256)": { - "details": "In case depositing in stBTC vault fails (e.g. because of the maximum deposit limit being reached), the `queueStake` function should be called to add the stake request to the staking queue.", - "params": { - "depositKey": "Deposit key identifying the deposit." - } - }, - "initializeStake((bytes4,bytes,bytes,bytes4),(uint32,bytes8,bytes20,bytes20,bytes4,address),address,uint16)": { - "details": "Requirements: - The revealed vault address must match the TBTCVault address, - All requirements from {Bridge#revealDepositWithExtraData} function must be met. - `staker` must be the staker address used in the P2(W)SH BTC deposit transaction as part of the extra data. - `referral` must be the referral info used in the P2(W)SH BTC deposit transaction as part of the extra data. - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex` can be revealed only one time.", - "params": { - "fundingTx": "Bitcoin funding transaction data, see `IBridgeTypes.BitcoinTxInfo`.", - "referral": "Data used for referral program.", - "reveal": "Deposit reveal data, see `IBridgeTypes.DepositRevealInfo`.", - "staker": "The address to which the stBTC shares will be minted." - } - }, - "owner()": { - "details": "Returns the address of the current owner." - }, - "pendingOwner()": { - "details": "Returns the address of the pending owner." - }, - "queueStake(uint256)": { - "details": "It queues the stake request, until the stBTC vault is ready to accept the deposit. The request must be finalized with `finalizeQueuedStake` after the limit is increased or other user withdraws their funds from the stBTC contract to make place for another deposit. The staker has a possibility to submit `cancelQueuedStake` that will withdraw the minted tBTC token and abort staking process.", - "params": { - "depositKey": "Deposit key identifying the deposit." - } - }, - "renounceOwnership()": { - "details": "Leaves the contract without owner. It will not be possible to call `onlyOwner` functions. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby disabling any functionality that is only available to the owner." - }, - "transferOwnership(address)": { - "details": "Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. Can only be called by the current owner." - }, - "updateDepositorFeeDivisor(uint64)": { - "params": { - "newDepositorFeeDivisor": "New depositor fee divisor value." - } - } - }, - "stateVariables": { - "depositorFeeDivisor": { - "details": "That fee is computed as follows: `depositorFee = depositedAmount / depositorFeeDivisor` for example, if the depositor fee needs to be 2% of each deposit, the `depositorFeeDivisor` should be set to `50` because `1/50 = 0.02 = 2%`." - }, - "stakeRequests": { - "details": "The key is a deposit key identifying the deposit." - } - }, - "title": "Acre Bitcoin Depositor contract.", - "version": 1 - }, - "userdoc": { - "errors": { - "StbtcZeroAddress()": [ - { - "notice": "Reverts if the stBTC address is zero." - } - ], - "TbtcTokenZeroAddress()": [ - { - "notice": "Reverts if the tBTC Token address is zero." - } - ] - }, - "events": { - "BridgingCompleted(uint256,address,uint16,uint256,uint256)": { - "notice": "Emitted when bridging completion has been notified." - }, - "DepositorFeeDivisorUpdated(uint64)": { - "notice": "Emitted when a depositor fee divisor is updated." - }, - "StakeRequestCancelledFromQueue(uint256,address,uint256)": { - "notice": "Emitted when a queued stake request is cancelled." - }, - "StakeRequestFinalized(uint256,address,uint256)": { - "notice": "Emitted when a stake request is finalized." - }, - "StakeRequestFinalizedFromQueue(uint256,address,uint256)": { - "notice": "Emitted when a stake request is finalized from the queue." - }, - "StakeRequestInitialized(uint256,address,address)": { - "notice": "Emitted when a stake request is initialized." - }, - "StakeRequestQueued(uint256,address,uint256)": { - "notice": "Emitted when a stake request is queued." - } - }, - "kind": "user", - "methods": { - "SATOSHI_MULTIPLIER()": { - "notice": "Multiplier to convert satoshi to TBTC token units." - }, - "bridge()": { - "notice": "Bridge contract address." - }, - "cancelQueuedStake(uint256)": { - "notice": "Cancel queued stake. The function can be called by the staker to recover tBTC that cannot be finalized to stake in stBTC contract due to a deposit limit being reached." - }, - "constructor": { - "notice": "Acre Bitcoin Depositor contract constructor." - }, - "decodeExtraData(bytes32)": { - "notice": "Decodes staker address and referral from extra data." - }, - "depositorFeeDivisor()": { - "notice": "Divisor used to compute the depositor fee taken from each deposit and transferred to the treasury upon stake request finalization." - }, - "encodeExtraData(address,uint16)": { - "notice": "Encodes staker address and referral as extra data." - }, - "finalizeQueuedStake(uint256)": { - "notice": "This function should be called for previously queued stake request, when stBTC vault is able to accept a deposit." - }, - "finalizeStake(uint256)": { - "notice": "This function should be called for previously initialized stake request, after tBTC bridging process was finalized. It stakes the tBTC from the given deposit into stBTC, emitting the stBTC shares to the staker specified in the deposit extra data and using the referral provided in the extra data." - }, - "initializeStake((bytes4,bytes,bytes,bytes4),(uint32,bytes8,bytes20,bytes20,bytes4,address),address,uint16)": { - "notice": "This function allows staking process initialization for a Bitcoin deposit made by an user with a P2(W)SH transaction. It uses the supplied information to reveal a deposit to the tBTC Bridge contract." - }, - "queueStake(uint256)": { - "notice": "This function should be called for previously initialized stake request, after tBTC bridging process was finalized, in case the `finalizeStake` failed due to stBTC vault deposit limit being reached." - }, - "stakeRequests(uint256)": { - "notice": "Mapping of stake requests." - }, - "stbtc()": { - "notice": "stBTC contract." - }, - "tbtcToken()": { - "notice": "tBTC Token contract." - }, - "tbtcVault()": { - "notice": "TBTCVault contract address." - }, - "updateDepositorFeeDivisor(uint64)": { - "notice": "Updates the depositor fee divisor." - } - }, - "notice": "The contract integrates Acre staking with tBTC minting. User who wants to stake BTC in Acre should submit a Bitcoin transaction to the most recently created off-chain ECDSA wallets of the tBTC Bridge using pay-to-script-hash (P2SH) or pay-to-witness-script-hash (P2WSH) containing hashed information about this Depositor contract address, and staker's Ethereum address. Then, the staker initiates tBTC minting by revealing their Ethereum address along with their deposit blinding factor, refund public key hash and refund locktime on the tBTC Bridge through this Depositor contract. The off-chain ECDSA wallet and Optimistic Minting bots listen for these sorts of messages and when they get one, they check the Bitcoin network to make sure the deposit lines up. Majority of tBTC minting is finalized by the Optimistic Minting process, where Minter bot initializes minting process and if there is no veto from the Guardians, the process is finalized and tBTC minted to the Depositor address. If the revealed deposit is not handled by the Optimistic Minting process the off-chain ECDSA wallet may decide to pick the deposit transaction for sweeping, and when the sweep operation is confirmed on the Bitcoin network, the tBTC Bridge and tBTC vault mint the tBTC token to the Depositor address. After tBTC is minted to the Depositor, on the stake finalization tBTC is staked in stBTC contract and stBTC shares are emitted to the staker.", - "version": 1 - }, - "storageLayout": { - "storage": [ - { - "astId": 2683, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "bridge", - "offset": 0, - "slot": "0", - "type": "t_contract(IBridge)3087" - }, - { - "astId": 2687, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "tbtcVault", - "offset": 0, - "slot": "1", - "type": "t_contract(ITBTCVault)3107" - }, - { - "astId": 2691, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "__gap", - "offset": 0, - "slot": "2", - "type": "t_array(t_uint256)47_storage" - }, - { - "astId": 3585, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "_owner", - "offset": 0, - "slot": "49", - "type": "t_address" - }, - { - "astId": 3733, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "_pendingOwner", - "offset": 0, - "slot": "50", - "type": "t_address" - }, - { - "astId": 8874, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "stakeRequests", - "offset": 0, - "slot": "51", - "type": "t_mapping(t_uint256,t_struct(StakeRequest)8868_storage)" - }, - { - "astId": 8878, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "tbtcToken", - "offset": 0, - "slot": "52", - "type": "t_contract(IERC20)4710" - }, - { - "astId": 8882, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "stbtc", - "offset": 0, - "slot": "53", - "type": "t_contract(stBTC)10351" - }, - { - "astId": 8885, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "depositorFeeDivisor", - "offset": 20, - "slot": "53", - "type": "t_uint64" - } - ], - "types": { - "t_address": { - "encoding": "inplace", - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_uint256)47_storage": { - "base": "t_uint256", - "encoding": "inplace", - "label": "uint256[47]", - "numberOfBytes": "1504" - }, - "t_contract(IBridge)3087": { - "encoding": "inplace", - "label": "contract IBridge", - "numberOfBytes": "20" - }, - "t_contract(IERC20)4710": { - "encoding": "inplace", - "label": "contract IERC20", - "numberOfBytes": "20" - }, - "t_contract(ITBTCVault)3107": { - "encoding": "inplace", - "label": "contract ITBTCVault", - "numberOfBytes": "20" - }, - "t_contract(stBTC)10351": { - "encoding": "inplace", - "label": "contract stBTC", - "numberOfBytes": "20" - }, - "t_enum(StakeRequestState)8860": { - "encoding": "inplace", - "label": "enum AcreBitcoinDepositor.StakeRequestState", - "numberOfBytes": "1" - }, - "t_mapping(t_uint256,t_struct(StakeRequest)8868_storage)": { - "encoding": "mapping", - "key": "t_uint256", - "label": "mapping(uint256 => struct AcreBitcoinDepositor.StakeRequest)", - "numberOfBytes": "32", - "value": "t_struct(StakeRequest)8868_storage" - }, - "t_struct(StakeRequest)8868_storage": { - "encoding": "inplace", - "label": "struct AcreBitcoinDepositor.StakeRequest", - "members": [ - { - "astId": 8863, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "state", - "offset": 0, - "slot": "0", - "type": "t_enum(StakeRequestState)8860" - }, - { - "astId": 8865, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "staker", - "offset": 1, - "slot": "0", - "type": "t_address" - }, - { - "astId": 8867, - "contract": "contracts/AcreBitcoinDepositor.sol:AcreBitcoinDepositor", - "label": "queuedAmount", - "offset": 21, - "slot": "0", - "type": "t_uint88" - } - ], - "numberOfBytes": "32" - }, - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint64": { - "encoding": "inplace", - "label": "uint64", - "numberOfBytes": "8" - }, - "t_uint88": { - "encoding": "inplace", - "label": "uint88", - "numberOfBytes": "11" - } - } - } -} \ No newline at end of file diff --git a/sdk/src/lib/ethereum/artifacts/sepolia/stBTC.json b/sdk/src/lib/ethereum/artifacts/sepolia/stBTC.json deleted file mode 100644 index ea1bf83ad..000000000 --- a/sdk/src/lib/ethereum/artifacts/sepolia/stBTC.json +++ /dev/null @@ -1,1642 +0,0 @@ -{ - "address": "0x1265bDDDd268daf903551cAf52800D758F8930c4", - "abi": [ - { - "inputs": [ - { - "internalType": "contract IERC20", - "name": "_tbtc", - "type": "address" - }, - { - "internalType": "address", - "name": "_treasury", - "type": "address" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "target", - "type": "address" - } - ], - "name": "AddressEmptyCode", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "AddressInsufficientBalance", - "type": "error" - }, - { - "inputs": [], - "name": "DisallowedAddress", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "spender", - "type": "address" - }, - { - "internalType": "uint256", - "name": "allowance", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "needed", - "type": "uint256" - } - ], - "name": "ERC20InsufficientAllowance", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "sender", - "type": "address" - }, - { - "internalType": "uint256", - "name": "balance", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "needed", - "type": "uint256" - } - ], - "name": "ERC20InsufficientBalance", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "approver", - "type": "address" - } - ], - "name": "ERC20InvalidApprover", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "receiver", - "type": "address" - } - ], - "name": "ERC20InvalidReceiver", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "sender", - "type": "address" - } - ], - "name": "ERC20InvalidSender", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "spender", - "type": "address" - } - ], - "name": "ERC20InvalidSpender", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "receiver", - "type": "address" - }, - { - "internalType": "uint256", - "name": "assets", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "max", - "type": "uint256" - } - ], - "name": "ERC4626ExceededMaxDeposit", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "receiver", - "type": "address" - }, - { - "internalType": "uint256", - "name": "shares", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "max", - "type": "uint256" - } - ], - "name": "ERC4626ExceededMaxMint", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "internalType": "uint256", - "name": "shares", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "max", - "type": "uint256" - } - ], - "name": "ERC4626ExceededMaxRedeem", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "internalType": "uint256", - "name": "assets", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "max", - "type": "uint256" - } - ], - "name": "ERC4626ExceededMaxWithdraw", - "type": "error" - }, - { - "inputs": [], - "name": "FailedInnerCall", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "amount", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "min", - "type": "uint256" - } - ], - "name": "LessThanMinDeposit", - "type": "error" - }, - { - "inputs": [], - "name": "MathOverflowedMulDiv", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - } - ], - "name": "OwnableInvalidOwner", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "OwnableUnauthorizedAccount", - "type": "error" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - } - ], - "name": "SafeERC20FailedOperation", - "type": "error" - }, - { - "inputs": [], - "name": "ZeroAddress", - "type": "error" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "spender", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "Approval", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "sender", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "assets", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "shares", - "type": "uint256" - } - ], - "name": "Deposit", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint256", - "name": "minimumDepositAmount", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "maximumTotalAssets", - "type": "uint256" - } - ], - "name": "DepositParametersUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "oldDispatcher", - "type": "address" - }, - { - "indexed": false, - "internalType": "address", - "name": "newDispatcher", - "type": "address" - } - ], - "name": "DispatcherUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "previousOwner", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "OwnershipTransferred", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "Transfer", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "treasury", - "type": "address" - } - ], - "name": "TreasuryUpdated", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "sender", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "receiver", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "assets", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "shares", - "type": "uint256" - } - ], - "name": "Withdraw", - "type": "event" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - }, - { - "internalType": "address", - "name": "spender", - "type": "address" - } - ], - "name": "allowance", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "spender", - "type": "address" - }, - { - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "approve", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "asset", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "assetsBalanceOf", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "account", - "type": "address" - } - ], - "name": "balanceOf", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "shares", - "type": "uint256" - } - ], - "name": "convertToAssets", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "assets", - "type": "uint256" - } - ], - "name": "convertToShares", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "decimals", - "outputs": [ - { - "internalType": "uint8", - "name": "", - "type": "uint8" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "assets", - "type": "uint256" - }, - { - "internalType": "address", - "name": "receiver", - "type": "address" - } - ], - "name": "deposit", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "depositParameters", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "dispatcher", - "outputs": [ - { - "internalType": "contract Dispatcher", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "name": "maxDeposit", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "receiver", - "type": "address" - } - ], - "name": "maxMint", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - } - ], - "name": "maxRedeem", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "owner", - "type": "address" - } - ], - "name": "maxWithdraw", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "maximumTotalAssets", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "minimumDepositAmount", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "shares", - "type": "uint256" - }, - { - "internalType": "address", - "name": "receiver", - "type": "address" - } - ], - "name": "mint", - "outputs": [ - { - "internalType": "uint256", - "name": "assets", - "type": "uint256" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "name", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "owner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "assets", - "type": "uint256" - } - ], - "name": "previewDeposit", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "shares", - "type": "uint256" - } - ], - "name": "previewMint", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "shares", - "type": "uint256" - } - ], - "name": "previewRedeem", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "assets", - "type": "uint256" - } - ], - "name": "previewWithdraw", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "shares", - "type": "uint256" - }, - { - "internalType": "address", - "name": "receiver", - "type": "address" - }, - { - "internalType": "address", - "name": "owner", - "type": "address" - } - ], - "name": "redeem", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "renounceOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "symbol", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "totalAssets", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "totalSupply", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "transfer", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "from", - "type": "address" - }, - { - "internalType": "address", - "name": "to", - "type": "address" - }, - { - "internalType": "uint256", - "name": "value", - "type": "uint256" - } - ], - "name": "transferFrom", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newOwner", - "type": "address" - } - ], - "name": "transferOwnership", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "treasury", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "_minimumDepositAmount", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "_maximumTotalAssets", - "type": "uint256" - } - ], - "name": "updateDepositParameters", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "contract Dispatcher", - "name": "newDispatcher", - "type": "address" - } - ], - "name": "updateDispatcher", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "newTreasury", - "type": "address" - } - ], - "name": "updateTreasury", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "assets", - "type": "uint256" - }, - { - "internalType": "address", - "name": "receiver", - "type": "address" - }, - { - "internalType": "address", - "name": "owner", - "type": "address" - } - ], - "name": "withdraw", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "nonpayable", - "type": "function" - } - ], - "transactionHash": "0x15d8cea2a1d7bc42ef13ac211cf8cc7c438c110432d8695f77b303b2eab1a1a1", - "receipt": { - "to": null, - "from": "0x2d154A5c7cE9939274b89bbCe9f5B069E57b09A8", - "contractAddress": "0x1265bDDDd268daf903551cAf52800D758F8930c4", - "transactionIndex": 101, - "gasUsed": "1808006", - "logsBloom": "0x00000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000001000000000000000000000000000000400000020000000000000000000800000000000400000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000420000012000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0x77d0307f9267df860ef36c26a33209c98922ef1699e8b6f3ceaa76627632b61a", - "transactionHash": "0x15d8cea2a1d7bc42ef13ac211cf8cc7c438c110432d8695f77b303b2eab1a1a1", - "logs": [ - { - "transactionIndex": 101, - "blockNumber": 5415166, - "transactionHash": "0x15d8cea2a1d7bc42ef13ac211cf8cc7c438c110432d8695f77b303b2eab1a1a1", - "address": "0x1265bDDDd268daf903551cAf52800D758F8930c4", - "topics": [ - "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", - "0x0000000000000000000000000000000000000000000000000000000000000000", - "0x0000000000000000000000002d154a5c7ce9939274b89bbce9f5b069e57b09a8" - ], - "data": "0x", - "logIndex": 343, - "blockHash": "0x77d0307f9267df860ef36c26a33209c98922ef1699e8b6f3ceaa76627632b61a" - } - ], - "blockNumber": 5415166, - "cumulativeGasUsed": "21174168", - "status": 1, - "byzantium": true - }, - "args": [ - "0x517f2982701695D4E52f1ECFBEf3ba31Df470161", - "0x2d154A5c7cE9939274b89bbCe9f5B069E57b09A8" - ], - "numDeployments": 1, - "solcInputHash": "ca2ee42c4a116704dc3eb0bec6d11bc6", - "metadata": "{\"compiler\":{\"version\":\"0.8.21+commit.d9974bed\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"contract IERC20\",\"name\":\"_tbtc\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_treasury\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"target\",\"type\":\"address\"}],\"name\":\"AddressEmptyCode\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"AddressInsufficientBalance\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"DisallowedAddress\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"allowance\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"needed\",\"type\":\"uint256\"}],\"name\":\"ERC20InsufficientAllowance\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"balance\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"needed\",\"type\":\"uint256\"}],\"name\":\"ERC20InsufficientBalance\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"approver\",\"type\":\"address\"}],\"name\":\"ERC20InvalidApprover\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"ERC20InvalidReceiver\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"}],\"name\":\"ERC20InvalidSender\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"ERC20InvalidSpender\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"}],\"name\":\"ERC4626ExceededMaxDeposit\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"}],\"name\":\"ERC4626ExceededMaxMint\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"}],\"name\":\"ERC4626ExceededMaxRedeem\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"max\",\"type\":\"uint256\"}],\"name\":\"ERC4626ExceededMaxWithdraw\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"FailedInnerCall\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"min\",\"type\":\"uint256\"}],\"name\":\"LessThanMinDeposit\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"MathOverflowedMulDiv\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"OwnableInvalidOwner\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"OwnableUnauthorizedAccount\",\"type\":\"error\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"token\",\"type\":\"address\"}],\"name\":\"SafeERC20FailedOperation\",\"type\":\"error\"},{\"inputs\":[],\"name\":\"ZeroAddress\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"Deposit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"minimumDepositAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"maximumTotalAssets\",\"type\":\"uint256\"}],\"name\":\"DepositParametersUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"oldDispatcher\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newDispatcher\",\"type\":\"address\"}],\"name\":\"DispatcherUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"treasury\",\"type\":\"address\"}],\"name\":\"TreasuryUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"Withdraw\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"asset\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"assetsBalanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"convertToAssets\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"convertToShares\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"deposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"depositParameters\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"dispatcher\",\"outputs\":[{\"internalType\":\"contract Dispatcher\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"maxDeposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"maxMint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"maxRedeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"maxWithdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"maximumTotalAssets\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"minimumDepositAmount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"mint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"previewDeposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"previewMint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"previewRedeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"previewWithdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"redeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalAssets\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"treasury\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_minimumDepositAmount\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"_maximumTotalAssets\",\"type\":\"uint256\"}],\"name\":\"updateDepositParameters\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contract Dispatcher\",\"name\":\"newDispatcher\",\"type\":\"address\"}],\"name\":\"updateDispatcher\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newTreasury\",\"type\":\"address\"}],\"name\":\"updateTreasury\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"withdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"details\":\"ERC-4626 is a standard to optimize and unify the technical parameters of yield-bearing vaults. This contract facilitates the minting and burning of shares (stBTC), which are represented as standard ERC20 tokens, providing a seamless exchange with tBTC tokens.\",\"errors\":{\"AddressEmptyCode(address)\":[{\"details\":\"There's no code at `target` (it is not a contract).\"}],\"AddressInsufficientBalance(address)\":[{\"details\":\"The ETH balance of the account is not enough to perform the operation.\"}],\"ERC20InsufficientAllowance(address,uint256,uint256)\":[{\"details\":\"Indicates a failure with the `spender`\\u2019s `allowance`. Used in transfers.\",\"params\":{\"allowance\":\"Amount of tokens a `spender` is allowed to operate with.\",\"needed\":\"Minimum amount required to perform a transfer.\",\"spender\":\"Address that may be allowed to operate on tokens without being their owner.\"}}],\"ERC20InsufficientBalance(address,uint256,uint256)\":[{\"details\":\"Indicates an error related to the current `balance` of a `sender`. Used in transfers.\",\"params\":{\"balance\":\"Current balance for the interacting account.\",\"needed\":\"Minimum amount required to perform a transfer.\",\"sender\":\"Address whose tokens are being transferred.\"}}],\"ERC20InvalidApprover(address)\":[{\"details\":\"Indicates a failure with the `approver` of a token to be approved. Used in approvals.\",\"params\":{\"approver\":\"Address initiating an approval operation.\"}}],\"ERC20InvalidReceiver(address)\":[{\"details\":\"Indicates a failure with the token `receiver`. Used in transfers.\",\"params\":{\"receiver\":\"Address to which tokens are being transferred.\"}}],\"ERC20InvalidSender(address)\":[{\"details\":\"Indicates a failure with the token `sender`. Used in transfers.\",\"params\":{\"sender\":\"Address whose tokens are being transferred.\"}}],\"ERC20InvalidSpender(address)\":[{\"details\":\"Indicates a failure with the `spender` to be approved. Used in approvals.\",\"params\":{\"spender\":\"Address that may be allowed to operate on tokens without being their owner.\"}}],\"ERC4626ExceededMaxDeposit(address,uint256,uint256)\":[{\"details\":\"Attempted to deposit more assets than the max amount for `receiver`.\"}],\"ERC4626ExceededMaxMint(address,uint256,uint256)\":[{\"details\":\"Attempted to mint more shares than the max amount for `receiver`.\"}],\"ERC4626ExceededMaxRedeem(address,uint256,uint256)\":[{\"details\":\"Attempted to redeem more shares than the max amount for `receiver`.\"}],\"ERC4626ExceededMaxWithdraw(address,uint256,uint256)\":[{\"details\":\"Attempted to withdraw more assets than the max amount for `receiver`.\"}],\"FailedInnerCall()\":[{\"details\":\"A call to an address target failed. The target may have reverted.\"}],\"LessThanMinDeposit(uint256,uint256)\":[{\"params\":{\"amount\":\"Amount to check.\",\"min\":\"Minimum amount to check 'amount' against.\"}}],\"MathOverflowedMulDiv()\":[{\"details\":\"Muldiv operation overflow.\"}],\"OwnableInvalidOwner(address)\":[{\"details\":\"The owner is not a valid owner account. (eg. `address(0)`)\"}],\"OwnableUnauthorizedAccount(address)\":[{\"details\":\"The caller account is not authorized to perform an operation.\"}],\"SafeERC20FailedOperation(address)\":[{\"details\":\"An operation with an ERC20 token failed.\"}]},\"events\":{\"Approval(address,address,uint256)\":{\"details\":\"Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance.\"},\"DepositParametersUpdated(uint256,uint256)\":{\"params\":{\"maximumTotalAssets\":\"New value of the maximum total assets amount.\",\"minimumDepositAmount\":\"New value of the minimum deposit amount.\"}},\"DispatcherUpdated(address,address)\":{\"params\":{\"newDispatcher\":\"Address of the new dispatcher contract.\",\"oldDispatcher\":\"Address of the old dispatcher contract.\"}},\"Transfer(address,address,uint256)\":{\"details\":\"Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero.\"},\"TreasuryUpdated(address)\":{\"params\":{\"treasury\":\"New treasury wallet address.\"}}},\"kind\":\"dev\",\"methods\":{\"allowance(address,address)\":{\"details\":\"See {IERC20-allowance}.\"},\"approve(address,uint256)\":{\"details\":\"See {IERC20-approve}. NOTE: If `value` is the maximum `uint256`, the allowance is not updated on `transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address.\"},\"asset()\":{\"details\":\"See {IERC4626-asset}. \"},\"assetsBalanceOf(address)\":{\"params\":{\"account\":\"Owner of shares.\"},\"returns\":{\"_0\":\"Assets amount.\"}},\"balanceOf(address)\":{\"details\":\"See {IERC20-balanceOf}.\"},\"convertToAssets(uint256)\":{\"details\":\"See {IERC4626-convertToAssets}. \"},\"convertToShares(uint256)\":{\"details\":\"See {IERC4626-convertToShares}. \"},\"decimals()\":{\"details\":\"Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This \\\"original\\\" value is cached during construction of the vault contract. If this read operation fails (e.g., the asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals. See {IERC20Metadata-decimals}.\"},\"deposit(uint256,address)\":{\"details\":\"Takes into account a deposit parameter, minimum deposit amount, which determines the minimum amount for a single deposit operation. The amount of the assets has to be pre-approved in the tBTC contract.\",\"params\":{\"assets\":\"Approved amount of tBTC tokens to deposit.\",\"receiver\":\"The address to which the shares will be minted.\"},\"returns\":{\"_0\":\"Minted shares.\"}},\"depositParameters()\":{\"returns\":{\"_0\":\"Returns deposit parameters.\"}},\"maxDeposit(address)\":{\"details\":\"When the remaining amount of unused limit is less than the minimum deposit amount, this function returns 0.\",\"returns\":{\"_0\":\"The maximum amount of tBTC token that can be deposited into Acre protocol for the receiver.\"}},\"maxMint(address)\":{\"details\":\"Since the stBTC contract limits the maximum total tBTC tokens this function converts the maximum deposit amount to shares.\",\"returns\":{\"_0\":\"The maximum amount of the vault shares.\"}},\"maxRedeem(address)\":{\"details\":\"See {IERC4626-maxRedeem}. \"},\"maxWithdraw(address)\":{\"details\":\"See {IERC4626-maxWithdraw}. \"},\"mint(uint256,address)\":{\"details\":\"Takes into account a deposit parameter, minimum deposit amount, which determines the minimum amount for a single deposit operation. The amount of the assets has to be pre-approved in the tBTC contract. The msg.sender is required to grant approval for tBTC transfer. To determine the total assets amount necessary for approval corresponding to a given share amount, use the `previewMint` function.\",\"params\":{\"receiver\":\"The address to which the shares will be minted.\",\"shares\":\"Amount of shares to mint.\"}},\"name()\":{\"details\":\"Returns the name of the token.\"},\"owner()\":{\"details\":\"Returns the address of the current owner.\"},\"previewDeposit(uint256)\":{\"details\":\"See {IERC4626-previewDeposit}. \"},\"previewMint(uint256)\":{\"details\":\"See {IERC4626-previewMint}. \"},\"previewRedeem(uint256)\":{\"details\":\"See {IERC4626-previewRedeem}. \"},\"previewWithdraw(uint256)\":{\"details\":\"See {IERC4626-previewWithdraw}. \"},\"redeem(uint256,address,address)\":{\"details\":\"See {IERC4626-redeem}. \"},\"renounceOwnership()\":{\"details\":\"Leaves the contract without owner. It will not be possible to call `onlyOwner` functions. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby disabling any functionality that is only available to the owner.\"},\"symbol()\":{\"details\":\"Returns the symbol of the token, usually a shorter version of the name.\"},\"totalAssets()\":{\"details\":\"See {IERC4626-totalAssets}. \"},\"totalSupply()\":{\"details\":\"See {IERC20-totalSupply}.\"},\"transfer(address,uint256)\":{\"details\":\"See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `value`.\"},\"transferFrom(address,address,uint256)\":{\"details\":\"See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowance is the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address. - `from` must have a balance of at least `value`. - the caller must have allowance for ``from``'s tokens of at least `value`.\"},\"transferOwnership(address)\":{\"details\":\"Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.\"},\"updateDepositParameters(uint256,uint256)\":{\"details\":\"To disable the limit for deposits, set the maximum total assets to maximum (`type(uint256).max`).\",\"params\":{\"_maximumTotalAssets\":\"New value of the maximum total assets amount. It is the maximum amount of the tBTC token that the Acre protocol can hold.\",\"_minimumDepositAmount\":\"New value of the minimum deposit amount. It is the minimum amount for a single deposit operation.\"}},\"updateDispatcher(address)\":{\"params\":{\"newDispatcher\":\"Address of the new dispatcher contract.\"}},\"updateTreasury(address)\":{\"params\":{\"newTreasury\":\"New treasury wallet address.\"}},\"withdraw(uint256,address,address)\":{\"details\":\"See {IERC4626-withdraw}. \"}},\"title\":\"stBTC\",\"version\":1},\"userdoc\":{\"errors\":{\"DisallowedAddress()\":[{\"notice\":\"Reverts if the address is disallowed.\"}],\"LessThanMinDeposit(uint256,uint256)\":[{\"notice\":\"Reverts if the amount is less than the minimum deposit amount.\"}],\"ZeroAddress()\":[{\"notice\":\"Reverts if the address is zero.\"}]},\"events\":{\"DepositParametersUpdated(uint256,uint256)\":{\"notice\":\"Emitted when deposit parameters are updated.\"},\"DispatcherUpdated(address,address)\":{\"notice\":\"Emitted when the dispatcher contract is updated.\"},\"TreasuryUpdated(address)\":{\"notice\":\"Emitted when the treasury wallet address is updated.\"}},\"kind\":\"user\",\"methods\":{\"assetsBalanceOf(address)\":{\"notice\":\"Returns value of assets that would be exchanged for the amount of shares owned by the `account`.\"},\"deposit(uint256,address)\":{\"notice\":\"Mints shares to receiver by depositing exactly amount of tBTC tokens.\"},\"dispatcher()\":{\"notice\":\"Dispatcher contract that routes tBTC from stBTC to a given vault and back.\"},\"maxDeposit(address)\":{\"notice\":\"Returns the maximum amount of the tBTC token that can be deposited into the vault for the receiver through a deposit call. It takes into account the deposit parameter, maximum total assets, which determines the total amount of tBTC token held by Acre protocol.\"},\"maxMint(address)\":{\"notice\":\"Returns the maximum amount of the vault shares that can be minted for the receiver, through a mint call.\"},\"maximumTotalAssets()\":{\"notice\":\"Maximum total amount of tBTC token held by Acre protocol.\"},\"minimumDepositAmount()\":{\"notice\":\"Minimum amount for a single deposit operation.\"},\"mint(uint256,address)\":{\"notice\":\"Mints shares to receiver by depositing tBTC tokens.\"},\"treasury()\":{\"notice\":\"Address of the treasury wallet, where fees should be transferred to.\"},\"updateDepositParameters(uint256,uint256)\":{\"notice\":\"Updates deposit parameters.\"},\"updateDispatcher(address)\":{\"notice\":\"Updates the dispatcher contract and gives it an unlimited allowance to transfer staked tBTC.\"},\"updateTreasury(address)\":{\"notice\":\"Updates treasury wallet address.\"}},\"notice\":\"This contract implements the ERC-4626 tokenized vault standard. By staking tBTC, users acquire a liquid staking token called stBTC, commonly referred to as \\\"shares\\\". The staked tBTC is securely deposited into Acre's vaults, where it generates yield over time. Users have the flexibility to redeem stBTC, enabling them to withdraw their staked tBTC along with the accrued yield.\",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/stBTC.sol\":\"stBTC\"},\"evmVersion\":\"paris\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":1000},\"remappings\":[]},\"sources\":{\"@openzeppelin/contracts/access/Ownable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {Context} from \\\"../utils/Context.sol\\\";\\n\\n/**\\n * @dev Contract module which provides a basic access control mechanism, where\\n * there is an account (an owner) that can be granted exclusive access to\\n * specific functions.\\n *\\n * The initial owner is set to the address provided by the deployer. This can\\n * later be changed with {transferOwnership}.\\n *\\n * This module is used through inheritance. It will make available the modifier\\n * `onlyOwner`, which can be applied to your functions to restrict their use to\\n * the owner.\\n */\\nabstract contract Ownable is Context {\\n address private _owner;\\n\\n /**\\n * @dev The caller account is not authorized to perform an operation.\\n */\\n error OwnableUnauthorizedAccount(address account);\\n\\n /**\\n * @dev The owner is not a valid owner account. (eg. `address(0)`)\\n */\\n error OwnableInvalidOwner(address owner);\\n\\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\\n\\n /**\\n * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\\n */\\n constructor(address initialOwner) {\\n if (initialOwner == address(0)) {\\n revert OwnableInvalidOwner(address(0));\\n }\\n _transferOwnership(initialOwner);\\n }\\n\\n /**\\n * @dev Throws if called by any account other than the owner.\\n */\\n modifier onlyOwner() {\\n _checkOwner();\\n _;\\n }\\n\\n /**\\n * @dev Returns the address of the current owner.\\n */\\n function owner() public view virtual returns (address) {\\n return _owner;\\n }\\n\\n /**\\n * @dev Throws if the sender is not the owner.\\n */\\n function _checkOwner() internal view virtual {\\n if (owner() != _msgSender()) {\\n revert OwnableUnauthorizedAccount(_msgSender());\\n }\\n }\\n\\n /**\\n * @dev Leaves the contract without owner. It will not be possible to call\\n * `onlyOwner` functions. Can only be called by the current owner.\\n *\\n * NOTE: Renouncing ownership will leave the contract without an owner,\\n * thereby disabling any functionality that is only available to the owner.\\n */\\n function renounceOwnership() public virtual onlyOwner {\\n _transferOwnership(address(0));\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Can only be called by the current owner.\\n */\\n function transferOwnership(address newOwner) public virtual onlyOwner {\\n if (newOwner == address(0)) {\\n revert OwnableInvalidOwner(address(0));\\n }\\n _transferOwnership(newOwner);\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Internal function without access restriction.\\n */\\n function _transferOwnership(address newOwner) internal virtual {\\n address oldOwner = _owner;\\n _owner = newOwner;\\n emit OwnershipTransferred(oldOwner, newOwner);\\n }\\n}\\n\",\"keccak256\":\"0xff6d0bb2e285473e5311d9d3caacb525ae3538a80758c10649a4d61029b017bb\",\"license\":\"MIT\"},\"@openzeppelin/contracts/interfaces/IERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../token/ERC20/IERC20.sol\\\";\\nimport {IERC20Metadata} from \\\"../token/ERC20/extensions/IERC20Metadata.sol\\\";\\n\\n/**\\n * @dev Interface of the ERC4626 \\\"Tokenized Vault Standard\\\", as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\\n */\\ninterface IERC4626 is IERC20, IERC20Metadata {\\n event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\\n\\n event Withdraw(\\n address indexed sender,\\n address indexed receiver,\\n address indexed owner,\\n uint256 assets,\\n uint256 shares\\n );\\n\\n /**\\n * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\\n *\\n * - MUST be an ERC-20 token contract.\\n * - MUST NOT revert.\\n */\\n function asset() external view returns (address assetTokenAddress);\\n\\n /**\\n * @dev Returns the total amount of the underlying asset that is \\u201cmanaged\\u201d by Vault.\\n *\\n * - SHOULD include any compounding that occurs from yield.\\n * - MUST be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT revert.\\n */\\n function totalAssets() external view returns (uint256 totalManagedAssets);\\n\\n /**\\n * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToShares(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\\n * through a deposit call.\\n *\\n * - MUST return a limited value if receiver is subject to some deposit limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\\n * - MUST NOT revert.\\n */\\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\\n * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\\n * in the same transaction.\\n * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\\n * deposit would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * deposit execution, and are accounted for during deposit.\\n * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\\n * - MUST return a limited value if receiver is subject to some mint limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\\n * - MUST NOT revert.\\n */\\n function maxMint(address receiver) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\\n * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\\n * same transaction.\\n * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\\n * would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by minting.\\n */\\n function previewMint(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\\n * execution, and are accounted for during mint.\\n * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\\n * Vault, through a withdraw call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\\n * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\\n * called\\n * in the same transaction.\\n * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\\n * the withdrawal would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * withdraw execution, and are accounted for during withdraw.\\n * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\\n * through a redeem call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxRedeem(address owner) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\\n * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\\n * same transaction.\\n * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\\n * redemption would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\\n */\\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * redeem execution, and are accounted for during redeem.\\n * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\\n}\\n\",\"keccak256\":\"0x207f64371bc0fcc5be86713aa5da109a870cc3a6da50e93b64ee881e369b593d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Standard ERC20 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.\\n */\\ninterface IERC20Errors {\\n /**\\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param balance Current balance for the interacting account.\\n * @param needed Minimum amount required to perform a transfer.\\n */\\n error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC20InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC20InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `spender`\\u2019s `allowance`. Used in transfers.\\n * @param spender Address that may be allowed to operate on tokens without being their owner.\\n * @param allowance Amount of tokens a `spender` is allowed to operate with.\\n * @param needed Minimum amount required to perform a transfer.\\n */\\n error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC20InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\\n * @param spender Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC20InvalidSpender(address spender);\\n}\\n\\n/**\\n * @dev Standard ERC721 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.\\n */\\ninterface IERC721Errors {\\n /**\\n * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.\\n * Used in balance queries.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC721InvalidOwner(address owner);\\n\\n /**\\n * @dev Indicates a `tokenId` whose `owner` is the zero address.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC721NonexistentToken(uint256 tokenId);\\n\\n /**\\n * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param tokenId Identifier number of a token.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC721InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC721InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `operator`\\u2019s approval. Used in transfers.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC721InsufficientApproval(address operator, uint256 tokenId);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC721InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC721InvalidOperator(address operator);\\n}\\n\\n/**\\n * @dev Standard ERC1155 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.\\n */\\ninterface IERC1155Errors {\\n /**\\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n * @param balance Current balance for the interacting account.\\n * @param needed Minimum amount required to perform a transfer.\\n * @param tokenId Identifier number of a token.\\n */\\n error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\\n\\n /**\\n * @dev Indicates a failure with the token `sender`. Used in transfers.\\n * @param sender Address whose tokens are being transferred.\\n */\\n error ERC1155InvalidSender(address sender);\\n\\n /**\\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n * @param receiver Address to which tokens are being transferred.\\n */\\n error ERC1155InvalidReceiver(address receiver);\\n\\n /**\\n * @dev Indicates a failure with the `operator`\\u2019s approval. Used in transfers.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n * @param owner Address of the current owner of a token.\\n */\\n error ERC1155MissingApprovalForAll(address operator, address owner);\\n\\n /**\\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n * @param approver Address initiating an approval operation.\\n */\\n error ERC1155InvalidApprover(address approver);\\n\\n /**\\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\\n * @param operator Address that may be allowed to operate on tokens without being their owner.\\n */\\n error ERC1155InvalidOperator(address operator);\\n\\n /**\\n * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\\n * Used in batch transfers.\\n * @param idsLength Length of the array of token identifiers\\n * @param valuesLength Length of the array of token amounts\\n */\\n error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\\n}\\n\",\"keccak256\":\"0x60c65f701957fdd6faea1acb0bb45825791d473693ed9ecb34726fdfaa849dd7\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/ERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"./IERC20.sol\\\";\\nimport {IERC20Metadata} from \\\"./extensions/IERC20Metadata.sol\\\";\\nimport {Context} from \\\"../../utils/Context.sol\\\";\\nimport {IERC20Errors} from \\\"../../interfaces/draft-IERC6093.sol\\\";\\n\\n/**\\n * @dev Implementation of the {IERC20} interface.\\n *\\n * This implementation is agnostic to the way tokens are created. This means\\n * that a supply mechanism has to be added in a derived contract using {_mint}.\\n *\\n * TIP: For a detailed writeup see our guide\\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\\n * to implement supply mechanisms].\\n *\\n * The default value of {decimals} is 18. To change this, you should override\\n * this function so it returns a different value.\\n *\\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\\n * instead returning `false` on failure. This behavior is nonetheless\\n * conventional and does not conflict with the expectations of ERC20\\n * applications.\\n *\\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\\n * This allows applications to reconstruct the allowance for all accounts just\\n * by listening to said events. Other implementations of the EIP may not emit\\n * these events, as it isn't required by the specification.\\n */\\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\\n mapping(address account => uint256) private _balances;\\n\\n mapping(address account => mapping(address spender => uint256)) private _allowances;\\n\\n uint256 private _totalSupply;\\n\\n string private _name;\\n string private _symbol;\\n\\n /**\\n * @dev Sets the values for {name} and {symbol}.\\n *\\n * All two of these values are immutable: they can only be set once during\\n * construction.\\n */\\n constructor(string memory name_, string memory symbol_) {\\n _name = name_;\\n _symbol = symbol_;\\n }\\n\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() public view virtual returns (string memory) {\\n return _name;\\n }\\n\\n /**\\n * @dev Returns the symbol of the token, usually a shorter version of the\\n * name.\\n */\\n function symbol() public view virtual returns (string memory) {\\n return _symbol;\\n }\\n\\n /**\\n * @dev Returns the number of decimals used to get its user representation.\\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\\n *\\n * Tokens usually opt for a value of 18, imitating the relationship between\\n * Ether and Wei. This is the default value returned by this function, unless\\n * it's overridden.\\n *\\n * NOTE: This information is only used for _display_ purposes: it in\\n * no way affects any of the arithmetic of the contract, including\\n * {IERC20-balanceOf} and {IERC20-transfer}.\\n */\\n function decimals() public view virtual returns (uint8) {\\n return 18;\\n }\\n\\n /**\\n * @dev See {IERC20-totalSupply}.\\n */\\n function totalSupply() public view virtual returns (uint256) {\\n return _totalSupply;\\n }\\n\\n /**\\n * @dev See {IERC20-balanceOf}.\\n */\\n function balanceOf(address account) public view virtual returns (uint256) {\\n return _balances[account];\\n }\\n\\n /**\\n * @dev See {IERC20-transfer}.\\n *\\n * Requirements:\\n *\\n * - `to` cannot be the zero address.\\n * - the caller must have a balance of at least `value`.\\n */\\n function transfer(address to, uint256 value) public virtual returns (bool) {\\n address owner = _msgSender();\\n _transfer(owner, to, value);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-allowance}.\\n */\\n function allowance(address owner, address spender) public view virtual returns (uint256) {\\n return _allowances[owner][spender];\\n }\\n\\n /**\\n * @dev See {IERC20-approve}.\\n *\\n * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\\n * `transferFrom`. This is semantically equivalent to an infinite approval.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n */\\n function approve(address spender, uint256 value) public virtual returns (bool) {\\n address owner = _msgSender();\\n _approve(owner, spender, value);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-transferFrom}.\\n *\\n * Emits an {Approval} event indicating the updated allowance. This is not\\n * required by the EIP. See the note at the beginning of {ERC20}.\\n *\\n * NOTE: Does not update the allowance if the current allowance\\n * is the maximum `uint256`.\\n *\\n * Requirements:\\n *\\n * - `from` and `to` cannot be the zero address.\\n * - `from` must have a balance of at least `value`.\\n * - the caller must have allowance for ``from``'s tokens of at least\\n * `value`.\\n */\\n function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\\n address spender = _msgSender();\\n _spendAllowance(from, spender, value);\\n _transfer(from, to, value);\\n return true;\\n }\\n\\n /**\\n * @dev Moves a `value` amount of tokens from `from` to `to`.\\n *\\n * This internal function is equivalent to {transfer}, and can be used to\\n * e.g. implement automatic token fees, slashing mechanisms, etc.\\n *\\n * Emits a {Transfer} event.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead.\\n */\\n function _transfer(address from, address to, uint256 value) internal {\\n if (from == address(0)) {\\n revert ERC20InvalidSender(address(0));\\n }\\n if (to == address(0)) {\\n revert ERC20InvalidReceiver(address(0));\\n }\\n _update(from, to, value);\\n }\\n\\n /**\\n * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\\n * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\\n * this function.\\n *\\n * Emits a {Transfer} event.\\n */\\n function _update(address from, address to, uint256 value) internal virtual {\\n if (from == address(0)) {\\n // Overflow check required: The rest of the code assumes that totalSupply never overflows\\n _totalSupply += value;\\n } else {\\n uint256 fromBalance = _balances[from];\\n if (fromBalance < value) {\\n revert ERC20InsufficientBalance(from, fromBalance, value);\\n }\\n unchecked {\\n // Overflow not possible: value <= fromBalance <= totalSupply.\\n _balances[from] = fromBalance - value;\\n }\\n }\\n\\n if (to == address(0)) {\\n unchecked {\\n // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\\n _totalSupply -= value;\\n }\\n } else {\\n unchecked {\\n // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\\n _balances[to] += value;\\n }\\n }\\n\\n emit Transfer(from, to, value);\\n }\\n\\n /**\\n * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\\n * Relies on the `_update` mechanism\\n *\\n * Emits a {Transfer} event with `from` set to the zero address.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead.\\n */\\n function _mint(address account, uint256 value) internal {\\n if (account == address(0)) {\\n revert ERC20InvalidReceiver(address(0));\\n }\\n _update(address(0), account, value);\\n }\\n\\n /**\\n * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\\n * Relies on the `_update` mechanism.\\n *\\n * Emits a {Transfer} event with `to` set to the zero address.\\n *\\n * NOTE: This function is not virtual, {_update} should be overridden instead\\n */\\n function _burn(address account, uint256 value) internal {\\n if (account == address(0)) {\\n revert ERC20InvalidSender(address(0));\\n }\\n _update(account, address(0), value);\\n }\\n\\n /**\\n * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\\n *\\n * This internal function is equivalent to `approve`, and can be used to\\n * e.g. set automatic allowances for certain subsystems, etc.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `owner` cannot be the zero address.\\n * - `spender` cannot be the zero address.\\n *\\n * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\\n */\\n function _approve(address owner, address spender, uint256 value) internal {\\n _approve(owner, spender, value, true);\\n }\\n\\n /**\\n * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\\n *\\n * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\\n * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\\n * `Approval` event during `transferFrom` operations.\\n *\\n * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\\n * true using the following override:\\n * ```\\n * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\\n * super._approve(owner, spender, value, true);\\n * }\\n * ```\\n *\\n * Requirements are the same as {_approve}.\\n */\\n function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\\n if (owner == address(0)) {\\n revert ERC20InvalidApprover(address(0));\\n }\\n if (spender == address(0)) {\\n revert ERC20InvalidSpender(address(0));\\n }\\n _allowances[owner][spender] = value;\\n if (emitEvent) {\\n emit Approval(owner, spender, value);\\n }\\n }\\n\\n /**\\n * @dev Updates `owner` s allowance for `spender` based on spent `value`.\\n *\\n * Does not update the allowance value in case of infinite allowance.\\n * Revert if not enough allowance is available.\\n *\\n * Does not emit an {Approval} event.\\n */\\n function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\\n uint256 currentAllowance = allowance(owner, spender);\\n if (currentAllowance != type(uint256).max) {\\n if (currentAllowance < value) {\\n revert ERC20InsufficientAllowance(spender, currentAllowance, value);\\n }\\n unchecked {\\n _approve(owner, spender, currentAllowance - value, false);\\n }\\n }\\n }\\n}\\n\",\"keccak256\":\"0xc3e1fa9d1987f8d349dfb4d6fe93bf2ca014b52ba335cfac30bfe71e357e6f80\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/IERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Interface of the ERC20 standard as defined in the EIP.\\n */\\ninterface IERC20 {\\n /**\\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\\n * another (`to`).\\n *\\n * Note that `value` may be zero.\\n */\\n event Transfer(address indexed from, address indexed to, uint256 value);\\n\\n /**\\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\\n * a call to {approve}. `value` is the new allowance.\\n */\\n event Approval(address indexed owner, address indexed spender, uint256 value);\\n\\n /**\\n * @dev Returns the value of tokens in existence.\\n */\\n function totalSupply() external view returns (uint256);\\n\\n /**\\n * @dev Returns the value of tokens owned by `account`.\\n */\\n function balanceOf(address account) external view returns (uint256);\\n\\n /**\\n * @dev Moves a `value` amount of tokens from the caller's account to `to`.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transfer(address to, uint256 value) external returns (bool);\\n\\n /**\\n * @dev Returns the remaining number of tokens that `spender` will be\\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\\n * zero by default.\\n *\\n * This value changes when {approve} or {transferFrom} are called.\\n */\\n function allowance(address owner, address spender) external view returns (uint256);\\n\\n /**\\n * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\\n * caller's tokens.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\\n * that someone may use both the old and the new allowance by unfortunate\\n * transaction ordering. One possible solution to mitigate this race\\n * condition is to first reduce the spender's allowance to 0 and set the\\n * desired value afterwards:\\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\\n *\\n * Emits an {Approval} event.\\n */\\n function approve(address spender, uint256 value) external returns (bool);\\n\\n /**\\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\\n * allowance mechanism. `value` is then deducted from the caller's\\n * allowance.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transferFrom(address from, address to, uint256 value) external returns (bool);\\n}\\n\",\"keccak256\":\"0xc6a8ff0ea489379b61faa647490411b80102578440ab9d84e9a957cc12164e70\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20, IERC20Metadata, ERC20} from \\\"../ERC20.sol\\\";\\nimport {SafeERC20} from \\\"../utils/SafeERC20.sol\\\";\\nimport {IERC4626} from \\\"../../../interfaces/IERC4626.sol\\\";\\nimport {Math} from \\\"../../../utils/math/Math.sol\\\";\\n\\n/**\\n * @dev Implementation of the ERC4626 \\\"Tokenized Vault Standard\\\" as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].\\n *\\n * This extension allows the minting and burning of \\\"shares\\\" (represented using the ERC20 inheritance) in exchange for\\n * underlying \\\"assets\\\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\\n * the ERC20 standard. Any additional extensions included along it would affect the \\\"shares\\\" token represented by this\\n * contract and not the \\\"assets\\\" token which is an independent contract.\\n *\\n * [CAUTION]\\n * ====\\n * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning\\n * with a \\\"donation\\\" to the vault that inflates the price of a share. This is variously known as a donation or inflation\\n * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial\\n * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may\\n * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by\\n * verifying the amount received is as expected, using a wrapper that performs these checks such as\\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\\n *\\n * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`\\n * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault\\n * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself\\n * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset\\n * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's\\n * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more\\n * expensive than it is profitable. More details about the underlying math can be found\\n * xref:erc4626.adoc#inflation-attack[here].\\n *\\n * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued\\n * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets\\n * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience\\n * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the\\n * `_convertToShares` and `_convertToAssets` functions.\\n *\\n * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].\\n * ====\\n */\\nabstract contract ERC4626 is ERC20, IERC4626 {\\n using Math for uint256;\\n\\n IERC20 private immutable _asset;\\n uint8 private immutable _underlyingDecimals;\\n\\n /**\\n * @dev Attempted to deposit more assets than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);\\n\\n /**\\n * @dev Attempted to mint more shares than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);\\n\\n /**\\n * @dev Attempted to withdraw more assets than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);\\n\\n /**\\n * @dev Attempted to redeem more shares than the max amount for `receiver`.\\n */\\n error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);\\n\\n /**\\n * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).\\n */\\n constructor(IERC20 asset_) {\\n (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\\n _underlyingDecimals = success ? assetDecimals : 18;\\n _asset = asset_;\\n }\\n\\n /**\\n * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\\n */\\n function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {\\n (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(\\n abi.encodeCall(IERC20Metadata.decimals, ())\\n );\\n if (success && encodedDecimals.length >= 32) {\\n uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));\\n if (returnedDecimals <= type(uint8).max) {\\n return (true, uint8(returnedDecimals));\\n }\\n }\\n return (false, 0);\\n }\\n\\n /**\\n * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This\\n * \\\"original\\\" value is cached during construction of the vault contract. If this read operation fails (e.g., the\\n * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.\\n *\\n * See {IERC20Metadata-decimals}.\\n */\\n function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {\\n return _underlyingDecimals + _decimalsOffset();\\n }\\n\\n /** @dev See {IERC4626-asset}. */\\n function asset() public view virtual returns (address) {\\n return address(_asset);\\n }\\n\\n /** @dev See {IERC4626-totalAssets}. */\\n function totalAssets() public view virtual returns (uint256) {\\n return _asset.balanceOf(address(this));\\n }\\n\\n /** @dev See {IERC4626-convertToShares}. */\\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-convertToAssets}. */\\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-maxDeposit}. */\\n function maxDeposit(address) public view virtual returns (uint256) {\\n return type(uint256).max;\\n }\\n\\n /** @dev See {IERC4626-maxMint}. */\\n function maxMint(address) public view virtual returns (uint256) {\\n return type(uint256).max;\\n }\\n\\n /** @dev See {IERC4626-maxWithdraw}. */\\n function maxWithdraw(address owner) public view virtual returns (uint256) {\\n return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-maxRedeem}. */\\n function maxRedeem(address owner) public view virtual returns (uint256) {\\n return balanceOf(owner);\\n }\\n\\n /** @dev See {IERC4626-previewDeposit}. */\\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-previewMint}. */\\n function previewMint(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Ceil);\\n }\\n\\n /** @dev See {IERC4626-previewWithdraw}. */\\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\\n return _convertToShares(assets, Math.Rounding.Ceil);\\n }\\n\\n /** @dev See {IERC4626-previewRedeem}. */\\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\\n return _convertToAssets(shares, Math.Rounding.Floor);\\n }\\n\\n /** @dev See {IERC4626-deposit}. */\\n function deposit(uint256 assets, address receiver) public virtual returns (uint256) {\\n uint256 maxAssets = maxDeposit(receiver);\\n if (assets > maxAssets) {\\n revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);\\n }\\n\\n uint256 shares = previewDeposit(assets);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-mint}.\\n *\\n * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.\\n * In this case, the shares will be minted without requiring any assets to be deposited.\\n */\\n function mint(uint256 shares, address receiver) public virtual returns (uint256) {\\n uint256 maxShares = maxMint(receiver);\\n if (shares > maxShares) {\\n revert ERC4626ExceededMaxMint(receiver, shares, maxShares);\\n }\\n\\n uint256 assets = previewMint(shares);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return assets;\\n }\\n\\n /** @dev See {IERC4626-withdraw}. */\\n function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {\\n uint256 maxAssets = maxWithdraw(owner);\\n if (assets > maxAssets) {\\n revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);\\n }\\n\\n uint256 shares = previewWithdraw(assets);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-redeem}. */\\n function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {\\n uint256 maxShares = maxRedeem(owner);\\n if (shares > maxShares) {\\n revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);\\n }\\n\\n uint256 assets = previewRedeem(shares);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return assets;\\n }\\n\\n /**\\n * @dev Internal conversion function (from assets to shares) with support for rounding direction.\\n */\\n function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {\\n return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);\\n }\\n\\n /**\\n * @dev Internal conversion function (from shares to assets) with support for rounding direction.\\n */\\n function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {\\n return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);\\n }\\n\\n /**\\n * @dev Deposit/mint common workflow.\\n */\\n function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {\\n // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the\\n // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\\n // assets are transferred and before the shares are minted, which is a valid state.\\n // slither-disable-next-line reentrancy-no-eth\\n SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);\\n _mint(receiver, shares);\\n\\n emit Deposit(caller, receiver, assets, shares);\\n }\\n\\n /**\\n * @dev Withdraw/redeem common workflow.\\n */\\n function _withdraw(\\n address caller,\\n address receiver,\\n address owner,\\n uint256 assets,\\n uint256 shares\\n ) internal virtual {\\n if (caller != owner) {\\n _spendAllowance(owner, caller, shares);\\n }\\n\\n // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\\n // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\\n // shares are burned and after the assets are transferred, which is a valid state.\\n _burn(owner, shares);\\n SafeERC20.safeTransfer(_asset, receiver, assets);\\n\\n emit Withdraw(caller, receiver, owner, assets, shares);\\n }\\n\\n function _decimalsOffset() internal view virtual returns (uint8) {\\n return 0;\\n }\\n}\\n\",\"keccak256\":\"0x1837547e04d5fe5334eeb77a345683c22995f1e7aa033020757ddf83a80fc72d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../IERC20.sol\\\";\\n\\n/**\\n * @dev Interface for the optional metadata functions from the ERC20 standard.\\n */\\ninterface IERC20Metadata is IERC20 {\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() external view returns (string memory);\\n\\n /**\\n * @dev Returns the symbol of the token.\\n */\\n function symbol() external view returns (string memory);\\n\\n /**\\n * @dev Returns the decimals places of the token.\\n */\\n function decimals() external view returns (uint8);\\n}\\n\",\"keccak256\":\"0xaa761817f6cd7892fcf158b3c776b34551cde36f48ff9703d53898bc45a94ea2\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\\n *\\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\\n * need to send a transaction, and thus is not required to hold Ether at all.\\n *\\n * ==== Security Considerations\\n *\\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\\n * generally recommended is:\\n *\\n * ```solidity\\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\\n * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\\n * doThing(..., value);\\n * }\\n *\\n * function doThing(..., uint256 value) public {\\n * token.safeTransferFrom(msg.sender, address(this), value);\\n * ...\\n * }\\n * ```\\n *\\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\\n * {SafeERC20-safeTransferFrom}).\\n *\\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\\n * contracts should have entry points that don't rely on permit.\\n */\\ninterface IERC20Permit {\\n /**\\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\\n * given ``owner``'s signed approval.\\n *\\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\\n * ordering also apply here.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n * - `deadline` must be a timestamp in the future.\\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\\n * over the EIP712-formatted function arguments.\\n * - the signature must use ``owner``'s current nonce (see {nonces}).\\n *\\n * For more information on the signature format, see the\\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\\n * section].\\n *\\n * CAUTION: See Security Considerations above.\\n */\\n function permit(\\n address owner,\\n address spender,\\n uint256 value,\\n uint256 deadline,\\n uint8 v,\\n bytes32 r,\\n bytes32 s\\n ) external;\\n\\n /**\\n * @dev Returns the current nonce for `owner`. This value must be\\n * included whenever a signature is generated for {permit}.\\n *\\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\\n * prevents a signature from being used multiple times.\\n */\\n function nonces(address owner) external view returns (uint256);\\n\\n /**\\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\\n */\\n // solhint-disable-next-line func-name-mixedcase\\n function DOMAIN_SEPARATOR() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0x6008dabfe393240d73d7dd7688033f72740d570aa422254d29a7dce8568f3aff\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport {IERC20} from \\\"../IERC20.sol\\\";\\nimport {IERC20Permit} from \\\"../extensions/IERC20Permit.sol\\\";\\nimport {Address} from \\\"../../../utils/Address.sol\\\";\\n\\n/**\\n * @title SafeERC20\\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\\n * contract returns false). Tokens that return no value (and instead revert or\\n * throw on failure) are also supported, non-reverting calls are assumed to be\\n * successful.\\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\\n */\\nlibrary SafeERC20 {\\n using Address for address;\\n\\n /**\\n * @dev An operation with an ERC20 token failed.\\n */\\n error SafeERC20FailedOperation(address token);\\n\\n /**\\n * @dev Indicates a failed `decreaseAllowance` request.\\n */\\n error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\\n\\n /**\\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful.\\n */\\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\\n _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\\n }\\n\\n /**\\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\\n */\\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\\n _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\\n }\\n\\n /**\\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful.\\n */\\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\\n uint256 oldAllowance = token.allowance(address(this), spender);\\n forceApprove(token, spender, oldAllowance + value);\\n }\\n\\n /**\\n * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\\n * value, non-reverting calls are assumed to be successful.\\n */\\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\\n unchecked {\\n uint256 currentAllowance = token.allowance(address(this), spender);\\n if (currentAllowance < requestedDecrease) {\\n revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\\n }\\n forceApprove(token, spender, currentAllowance - requestedDecrease);\\n }\\n }\\n\\n /**\\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\\n * to be set to zero before setting it to a non-zero value, such as USDT.\\n */\\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\\n bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\\n\\n if (!_callOptionalReturnBool(token, approvalCall)) {\\n _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\\n _callOptionalReturn(token, approvalCall);\\n }\\n }\\n\\n /**\\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\\n * on the return value: the return value is optional (but if data is returned, it must not be false).\\n * @param token The token targeted by the call.\\n * @param data The call data (encoded using abi.encode or one of its variants).\\n */\\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\\n // the target address contains contract code and also asserts for success in the low-level call.\\n\\n bytes memory returndata = address(token).functionCall(data);\\n if (returndata.length != 0 && !abi.decode(returndata, (bool))) {\\n revert SafeERC20FailedOperation(address(token));\\n }\\n }\\n\\n /**\\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\\n * on the return value: the return value is optional (but if data is returned, it must not be false).\\n * @param token The token targeted by the call.\\n * @param data The call data (encoded using abi.encode or one of its variants).\\n *\\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\\n */\\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\\n // and not revert is the subcall reverts.\\n\\n (bool success, bytes memory returndata) = address(token).call(data);\\n return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;\\n }\\n}\\n\",\"keccak256\":\"0x37bb49513c49c87c4642a891b13b63571bc87013dde806617aa1efb54605f386\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Address.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary Address {\\n /**\\n * @dev The ETH balance of the account is not enough to perform the operation.\\n */\\n error AddressInsufficientBalance(address account);\\n\\n /**\\n * @dev There's no code at `target` (it is not a contract).\\n */\\n error AddressEmptyCode(address target);\\n\\n /**\\n * @dev A call to an address target failed. The target may have reverted.\\n */\\n error FailedInnerCall();\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n if (address(this).balance < amount) {\\n revert AddressInsufficientBalance(address(this));\\n }\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n if (!success) {\\n revert FailedInnerCall();\\n }\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason or custom error, it is bubbled\\n * up by this function (like regular Solidity function calls). However, if\\n * the call reverted with no returned reason, this function reverts with a\\n * {FailedInnerCall} error.\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n */\\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\\n if (address(this).balance < value) {\\n revert AddressInsufficientBalance(address(this));\\n }\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a delegate call.\\n */\\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.delegatecall(data);\\n return verifyCallResultFromTarget(target, success, returndata);\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\\n * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\\n * unsuccessful call.\\n */\\n function verifyCallResultFromTarget(\\n address target,\\n bool success,\\n bytes memory returndata\\n ) internal view returns (bytes memory) {\\n if (!success) {\\n _revert(returndata);\\n } else {\\n // only check if target is a contract if the call was successful and the return data is empty\\n // otherwise we already know that it was a contract\\n if (returndata.length == 0 && target.code.length == 0) {\\n revert AddressEmptyCode(target);\\n }\\n return returndata;\\n }\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\\n * revert reason or with a default {FailedInnerCall} error.\\n */\\n function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\\n if (!success) {\\n _revert(returndata);\\n } else {\\n return returndata;\\n }\\n }\\n\\n /**\\n * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\\n */\\n function _revert(bytes memory returndata) private pure {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n /// @solidity memory-safe-assembly\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert FailedInnerCall();\\n }\\n }\\n}\\n\",\"keccak256\":\"0xaf28a975a78550e45f65e559a3ad6a5ad43b9b8a37366999abd1b7084eb70721\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Context.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Provides information about the current execution context, including the\\n * sender of the transaction and its data. While these are generally available\\n * via msg.sender and msg.data, they should not be accessed in such a direct\\n * manner, since when dealing with meta-transactions the account sending and\\n * paying for execution may not be the actual sender (as far as an application\\n * is concerned).\\n *\\n * This contract is only required for intermediate, library-like contracts.\\n */\\nabstract contract Context {\\n function _msgSender() internal view virtual returns (address) {\\n return msg.sender;\\n }\\n\\n function _msgData() internal view virtual returns (bytes calldata) {\\n return msg.data;\\n }\\n}\\n\",\"keccak256\":\"0x75a4ee64c68dbd5f38bddd06e664a64c8271b4caa554fb6f0607dfd672bb4bf3\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/math/Math.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Standard math utilities missing in the Solidity language.\\n */\\nlibrary Math {\\n /**\\n * @dev Muldiv operation overflow.\\n */\\n error MathOverflowedMulDiv();\\n\\n enum Rounding {\\n Floor, // Toward negative infinity\\n Ceil, // Toward positive infinity\\n Trunc, // Toward zero\\n Expand // Away from zero\\n }\\n\\n /**\\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\\n */\\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n uint256 c = a + b;\\n if (c < a) return (false, 0);\\n return (true, c);\\n }\\n }\\n\\n /**\\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\\n */\\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b > a) return (false, 0);\\n return (true, a - b);\\n }\\n }\\n\\n /**\\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\\n */\\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\\n // benefit is lost if 'b' is also tested.\\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\\n if (a == 0) return (true, 0);\\n uint256 c = a * b;\\n if (c / a != b) return (false, 0);\\n return (true, c);\\n }\\n }\\n\\n /**\\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\\n */\\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b == 0) return (false, 0);\\n return (true, a / b);\\n }\\n }\\n\\n /**\\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\\n */\\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\\n unchecked {\\n if (b == 0) return (false, 0);\\n return (true, a % b);\\n }\\n }\\n\\n /**\\n * @dev Returns the largest of two numbers.\\n */\\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a > b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the smallest of two numbers.\\n */\\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a < b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the average of two numbers. The result is rounded towards\\n * zero.\\n */\\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\\n // (a + b) / 2 can overflow.\\n return (a & b) + (a ^ b) / 2;\\n }\\n\\n /**\\n * @dev Returns the ceiling of the division of two numbers.\\n *\\n * This differs from standard division with `/` in that it rounds towards infinity instead\\n * of rounding towards zero.\\n */\\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\\n if (b == 0) {\\n // Guarantee the same behavior as in a regular Solidity division.\\n return a / b;\\n }\\n\\n // (a + b - 1) / b can overflow on addition, so we distribute.\\n return a == 0 ? 0 : (a - 1) / b + 1;\\n }\\n\\n /**\\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\\n * denominator == 0.\\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\\n * Uniswap Labs also under MIT license.\\n */\\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\\n unchecked {\\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\\n // variables such that product = prod1 * 2^256 + prod0.\\n uint256 prod0 = x * y; // Least significant 256 bits of the product\\n uint256 prod1; // Most significant 256 bits of the product\\n assembly {\\n let mm := mulmod(x, y, not(0))\\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\\n }\\n\\n // Handle non-overflow cases, 256 by 256 division.\\n if (prod1 == 0) {\\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\\n // The surrounding unchecked block does not change this fact.\\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\\n return prod0 / denominator;\\n }\\n\\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\\n if (denominator <= prod1) {\\n revert MathOverflowedMulDiv();\\n }\\n\\n ///////////////////////////////////////////////\\n // 512 by 256 division.\\n ///////////////////////////////////////////////\\n\\n // Make division exact by subtracting the remainder from [prod1 prod0].\\n uint256 remainder;\\n assembly {\\n // Compute remainder using mulmod.\\n remainder := mulmod(x, y, denominator)\\n\\n // Subtract 256 bit number from 512 bit number.\\n prod1 := sub(prod1, gt(remainder, prod0))\\n prod0 := sub(prod0, remainder)\\n }\\n\\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\\n // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\\n\\n uint256 twos = denominator & (0 - denominator);\\n assembly {\\n // Divide denominator by twos.\\n denominator := div(denominator, twos)\\n\\n // Divide [prod1 prod0] by twos.\\n prod0 := div(prod0, twos)\\n\\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\\n twos := add(div(sub(0, twos), twos), 1)\\n }\\n\\n // Shift in bits from prod1 into prod0.\\n prod0 |= prod1 * twos;\\n\\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\\n // four bits. That is, denominator * inv = 1 mod 2^4.\\n uint256 inverse = (3 * denominator) ^ 2;\\n\\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\\n // works in modular arithmetic, doubling the correct bits in each step.\\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\\n\\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\\n // is no longer required.\\n result = prod0 * inverse;\\n return result;\\n }\\n }\\n\\n /**\\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\\n */\\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\\n uint256 result = mulDiv(x, y, denominator);\\n if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\\n result += 1;\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\\n * towards zero.\\n *\\n * Inspired by Henry S. Warren, Jr.'s \\\"Hacker's Delight\\\" (Chapter 11).\\n */\\n function sqrt(uint256 a) internal pure returns (uint256) {\\n if (a == 0) {\\n return 0;\\n }\\n\\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\\n //\\n // We know that the \\\"msb\\\" (most significant bit) of our target number `a` is a power of 2 such that we have\\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\\n //\\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\\n // \\u2192 `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\\n // \\u2192 `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\\n //\\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\\n uint256 result = 1 << (log2(a) >> 1);\\n\\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\\n // into the expected uint128 result.\\n unchecked {\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n return min(result, a / result);\\n }\\n }\\n\\n /**\\n * @notice Calculates sqrt(a), following the selected rounding direction.\\n */\\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = sqrt(a);\\n return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 2 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 128;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 64;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 32;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 16;\\n }\\n if (value >> 8 > 0) {\\n value >>= 8;\\n result += 8;\\n }\\n if (value >> 4 > 0) {\\n value >>= 4;\\n result += 4;\\n }\\n if (value >> 2 > 0) {\\n value >>= 2;\\n result += 2;\\n }\\n if (value >> 1 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log2(value);\\n return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 10 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >= 10 ** 64) {\\n value /= 10 ** 64;\\n result += 64;\\n }\\n if (value >= 10 ** 32) {\\n value /= 10 ** 32;\\n result += 32;\\n }\\n if (value >= 10 ** 16) {\\n value /= 10 ** 16;\\n result += 16;\\n }\\n if (value >= 10 ** 8) {\\n value /= 10 ** 8;\\n result += 8;\\n }\\n if (value >= 10 ** 4) {\\n value /= 10 ** 4;\\n result += 4;\\n }\\n if (value >= 10 ** 2) {\\n value /= 10 ** 2;\\n result += 2;\\n }\\n if (value >= 10 ** 1) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log10(value);\\n return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 256 of a positive value rounded towards zero.\\n * Returns 0 if given 0.\\n *\\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\\n */\\n function log256(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 16;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 8;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 4;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 2;\\n }\\n if (value >> 8 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log256(value);\\n return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\\n */\\n function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\\n return uint8(rounding) % 2 == 1;\\n }\\n}\\n\",\"keccak256\":\"0x005ec64c6313f0555d59e278f9a7a5ab2db5bdc72a027f255a37c327af1ec02d\",\"license\":\"MIT\"},\"contracts/Dispatcher.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/access/Ownable.sol\\\";\\nimport \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport \\\"@openzeppelin/contracts/interfaces/IERC4626.sol\\\";\\nimport \\\"./Router.sol\\\";\\nimport \\\"./stBTC.sol\\\";\\n\\n/// @title Dispatcher\\n/// @notice Dispatcher is a contract that routes tBTC from stBTC to\\n/// yield vaults and back. Vaults supply yield strategies with tBTC that\\n/// generate yield for Bitcoin holders.\\ncontract Dispatcher is Router, Ownable {\\n using SafeERC20 for IERC20;\\n\\n /// Struct holds information about a vault.\\n struct VaultInfo {\\n bool authorized;\\n }\\n\\n /// The main stBTC contract holding tBTC deposited by stakers.\\n stBTC public immutable stbtc;\\n /// tBTC token contract.\\n IERC20 public immutable tbtc;\\n /// Address of the maintainer bot.\\n address public maintainer;\\n\\n /// Authorized Yield Vaults that implement ERC4626 standard. These\\n /// vaults deposit assets to yield strategies, e.g. Uniswap V3\\n /// WBTC/TBTC pool. Vault can be a part of Acre ecosystem or can be\\n /// implemented externally. As long as it complies with ERC4626\\n /// standard and is authorized by the owner it can be plugged into\\n /// Acre.\\n address[] public vaults;\\n /// Mapping of vaults to their information.\\n mapping(address => VaultInfo) public vaultsInfo;\\n\\n /// Emitted when a vault is authorized.\\n /// @param vault Address of the vault.\\n event VaultAuthorized(address indexed vault);\\n\\n /// Emitted when a vault is deauthorized.\\n /// @param vault Address of the vault.\\n event VaultDeauthorized(address indexed vault);\\n\\n /// Emitted when tBTC is routed to a vault.\\n /// @param vault Address of the vault.\\n /// @param amount Amount of tBTC.\\n /// @param sharesOut Amount of received shares.\\n event DepositAllocated(\\n address indexed vault,\\n uint256 amount,\\n uint256 sharesOut\\n );\\n\\n /// Emitted when the maintainer address is updated.\\n /// @param maintainer Address of the new maintainer.\\n event MaintainerUpdated(address indexed maintainer);\\n\\n /// Reverts if the vault is already authorized.\\n error VaultAlreadyAuthorized();\\n\\n /// Reverts if the vault is not authorized.\\n error VaultUnauthorized();\\n\\n /// Reverts if the caller is not the maintainer.\\n error NotMaintainer();\\n\\n /// Reverts if the address is zero.\\n error ZeroAddress();\\n\\n /// Modifier that reverts if the caller is not the maintainer.\\n modifier onlyMaintainer() {\\n if (msg.sender != maintainer) {\\n revert NotMaintainer();\\n }\\n _;\\n }\\n\\n constructor(stBTC _stbtc, IERC20 _tbtc) Ownable(msg.sender) {\\n stbtc = _stbtc;\\n tbtc = _tbtc;\\n }\\n\\n /// @notice Adds a vault to the list of authorized vaults.\\n /// @param vault Address of the vault to add.\\n function authorizeVault(address vault) external onlyOwner {\\n if (isVaultAuthorized(vault)) {\\n revert VaultAlreadyAuthorized();\\n }\\n\\n vaults.push(vault);\\n vaultsInfo[vault].authorized = true;\\n\\n emit VaultAuthorized(vault);\\n }\\n\\n /// @notice Removes a vault from the list of authorized vaults.\\n /// @param vault Address of the vault to remove.\\n function deauthorizeVault(address vault) external onlyOwner {\\n if (!isVaultAuthorized(vault)) {\\n revert VaultUnauthorized();\\n }\\n\\n vaultsInfo[vault].authorized = false;\\n\\n for (uint256 i = 0; i < vaults.length; i++) {\\n if (vaults[i] == vault) {\\n vaults[i] = vaults[vaults.length - 1];\\n // slither-disable-next-line costly-loop\\n vaults.pop();\\n break;\\n }\\n }\\n\\n emit VaultDeauthorized(vault);\\n }\\n\\n /// @notice Updates the maintainer address.\\n /// @param newMaintainer Address of the new maintainer.\\n function updateMaintainer(address newMaintainer) external onlyOwner {\\n if (newMaintainer == address(0)) {\\n revert ZeroAddress();\\n }\\n\\n maintainer = newMaintainer;\\n\\n emit MaintainerUpdated(maintainer);\\n }\\n\\n /// TODO: make this function internal once the allocation distribution is\\n /// implemented\\n /// @notice Routes tBTC from stBTC to a vault. Can be called by the maintainer\\n /// only.\\n /// @param vault Address of the vault to route the assets to.\\n /// @param amount Amount of tBTC to deposit.\\n /// @param minSharesOut Minimum amount of shares to receive.\\n function depositToVault(\\n address vault,\\n uint256 amount,\\n uint256 minSharesOut\\n ) public onlyMaintainer {\\n if (!isVaultAuthorized(vault)) {\\n revert VaultUnauthorized();\\n }\\n\\n // slither-disable-next-line arbitrary-send-erc20\\n tbtc.safeTransferFrom(address(stbtc), address(this), amount);\\n tbtc.forceApprove(address(vault), amount);\\n\\n uint256 sharesOut = deposit(\\n IERC4626(vault),\\n address(stbtc),\\n amount,\\n minSharesOut\\n );\\n // slither-disable-next-line reentrancy-events\\n emit DepositAllocated(vault, amount, sharesOut);\\n }\\n\\n /// @notice Returns the list of authorized vaults.\\n function getVaults() public view returns (address[] memory) {\\n return vaults;\\n }\\n\\n /// @notice Returns true if the vault is authorized.\\n /// @param vault Address of the vault to check.\\n function isVaultAuthorized(address vault) public view returns (bool) {\\n return vaultsInfo[vault].authorized;\\n }\\n\\n /// TODO: implement redeem() / withdraw() functions\\n}\\n\",\"keccak256\":\"0x0dd77692ab8c6059afa7b4a90f26733560b53fb66192e9912a2064103c5d41fb\",\"license\":\"GPL-3.0-only\"},\"contracts/Router.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/interfaces/IERC4626.sol\\\";\\n\\n/// @title Router\\n/// @notice Router is a contract that routes tBTC from stBTC to\\n/// a given vault and back. Vaults supply yield strategies with tBTC that\\n/// generate yield for Bitcoin holders.\\nabstract contract Router {\\n /// Thrown when amount of shares received is below the min set by caller.\\n /// @param vault Address of the vault.\\n /// @param sharesOut Amount of received shares.\\n /// @param minSharesOut Minimum amount of shares expected to receive.\\n error MinSharesError(\\n address vault,\\n uint256 sharesOut,\\n uint256 minSharesOut\\n );\\n\\n /// @notice Routes funds from stBTC to a vault. The amount of tBTC to\\n /// Shares of deposited tBTC are minted to the stBTC contract.\\n /// @param vault Address of the vault to route the funds to.\\n /// @param receiver Address of the receiver of the shares.\\n /// @param amount Amount of tBTC to deposit.\\n /// @param minSharesOut Minimum amount of shares to receive.\\n function deposit(\\n IERC4626 vault,\\n address receiver,\\n uint256 amount,\\n uint256 minSharesOut\\n ) internal returns (uint256 sharesOut) {\\n if ((sharesOut = vault.deposit(amount, receiver)) < minSharesOut) {\\n revert MinSharesError(address(vault), sharesOut, minSharesOut);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x520e27c613f1234755c23402524b048a81abd15222d7f318504992d490248812\",\"license\":\"GPL-3.0-only\"},\"contracts/stBTC.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-3.0-only\\npragma solidity ^0.8.21;\\n\\nimport \\\"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\\\";\\nimport \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport \\\"@openzeppelin/contracts/access/Ownable.sol\\\";\\nimport \\\"./Dispatcher.sol\\\";\\n\\n/// @title stBTC\\n/// @notice This contract implements the ERC-4626 tokenized vault standard. By\\n/// staking tBTC, users acquire a liquid staking token called stBTC,\\n/// commonly referred to as \\\"shares\\\". The staked tBTC is securely\\n/// deposited into Acre's vaults, where it generates yield over time.\\n/// Users have the flexibility to redeem stBTC, enabling them to\\n/// withdraw their staked tBTC along with the accrued yield.\\n/// @dev ERC-4626 is a standard to optimize and unify the technical parameters\\n/// of yield-bearing vaults. This contract facilitates the minting and\\n/// burning of shares (stBTC), which are represented as standard ERC20\\n/// tokens, providing a seamless exchange with tBTC tokens.\\ncontract stBTC is ERC4626, Ownable {\\n using SafeERC20 for IERC20;\\n\\n /// Dispatcher contract that routes tBTC from stBTC to a given vault and back.\\n Dispatcher public dispatcher;\\n\\n /// Address of the treasury wallet, where fees should be transferred to.\\n address public treasury;\\n\\n /// Minimum amount for a single deposit operation.\\n uint256 public minimumDepositAmount;\\n /// Maximum total amount of tBTC token held by Acre protocol.\\n uint256 public maximumTotalAssets;\\n\\n /// Emitted when the treasury wallet address is updated.\\n /// @param treasury New treasury wallet address.\\n event TreasuryUpdated(address treasury);\\n\\n /// Emitted when deposit parameters are updated.\\n /// @param minimumDepositAmount New value of the minimum deposit amount.\\n /// @param maximumTotalAssets New value of the maximum total assets amount.\\n event DepositParametersUpdated(\\n uint256 minimumDepositAmount,\\n uint256 maximumTotalAssets\\n );\\n\\n /// Emitted when the dispatcher contract is updated.\\n /// @param oldDispatcher Address of the old dispatcher contract.\\n /// @param newDispatcher Address of the new dispatcher contract.\\n event DispatcherUpdated(address oldDispatcher, address newDispatcher);\\n\\n /// Reverts if the amount is less than the minimum deposit amount.\\n /// @param amount Amount to check.\\n /// @param min Minimum amount to check 'amount' against.\\n error LessThanMinDeposit(uint256 amount, uint256 min);\\n\\n /// Reverts if the address is zero.\\n error ZeroAddress();\\n\\n /// Reverts if the address is disallowed.\\n error DisallowedAddress();\\n\\n constructor(\\n IERC20 _tbtc,\\n address _treasury\\n ) ERC4626(_tbtc) ERC20(\\\"Acre Staked Bitcoin\\\", \\\"stBTC\\\") Ownable(msg.sender) {\\n if (address(_treasury) == address(0)) {\\n revert ZeroAddress();\\n }\\n treasury = _treasury;\\n // TODO: Revisit the exact values closer to the launch.\\n minimumDepositAmount = 0.001 * 1e18; // 0.001 tBTC\\n maximumTotalAssets = 25 * 1e18; // 25 tBTC\\n }\\n\\n /// @notice Updates treasury wallet address.\\n /// @param newTreasury New treasury wallet address.\\n function updateTreasury(address newTreasury) external onlyOwner {\\n // TODO: Introduce a parameters update process.\\n if (newTreasury == address(0)) {\\n revert ZeroAddress();\\n }\\n if (newTreasury == address(this)) {\\n revert DisallowedAddress();\\n }\\n treasury = newTreasury;\\n\\n emit TreasuryUpdated(newTreasury);\\n }\\n\\n /// @notice Updates deposit parameters.\\n /// @dev To disable the limit for deposits, set the maximum total assets to\\n /// maximum (`type(uint256).max`).\\n /// @param _minimumDepositAmount New value of the minimum deposit amount. It\\n /// is the minimum amount for a single deposit operation.\\n /// @param _maximumTotalAssets New value of the maximum total assets amount.\\n /// It is the maximum amount of the tBTC token that the Acre protocol\\n /// can hold.\\n function updateDepositParameters(\\n uint256 _minimumDepositAmount,\\n uint256 _maximumTotalAssets\\n ) external onlyOwner {\\n // TODO: Introduce a parameters update process.\\n minimumDepositAmount = _minimumDepositAmount;\\n maximumTotalAssets = _maximumTotalAssets;\\n\\n emit DepositParametersUpdated(\\n _minimumDepositAmount,\\n _maximumTotalAssets\\n );\\n }\\n\\n // TODO: Implement a governed upgrade process that initiates an update and\\n // then finalizes it after a delay.\\n /// @notice Updates the dispatcher contract and gives it an unlimited\\n /// allowance to transfer staked tBTC.\\n /// @param newDispatcher Address of the new dispatcher contract.\\n function updateDispatcher(Dispatcher newDispatcher) external onlyOwner {\\n if (address(newDispatcher) == address(0)) {\\n revert ZeroAddress();\\n }\\n\\n address oldDispatcher = address(dispatcher);\\n\\n emit DispatcherUpdated(oldDispatcher, address(newDispatcher));\\n dispatcher = newDispatcher;\\n\\n // TODO: Once withdrawal/rebalancing is implemented, we need to revoke the\\n // approval of the vaults share tokens from the old dispatcher and approve\\n // a new dispatcher to manage the share tokens.\\n\\n if (oldDispatcher != address(0)) {\\n // Setting allowance to zero for the old dispatcher\\n IERC20(asset()).forceApprove(oldDispatcher, 0);\\n }\\n\\n // Setting allowance to max for the new dispatcher\\n IERC20(asset()).forceApprove(address(dispatcher), type(uint256).max);\\n }\\n\\n /// @notice Mints shares to receiver by depositing exactly amount of\\n /// tBTC tokens.\\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\\n /// which determines the minimum amount for a single deposit operation.\\n /// The amount of the assets has to be pre-approved in the tBTC\\n /// contract.\\n /// @param assets Approved amount of tBTC tokens to deposit.\\n /// @param receiver The address to which the shares will be minted.\\n /// @return Minted shares.\\n function deposit(\\n uint256 assets,\\n address receiver\\n ) public override returns (uint256) {\\n if (assets < minimumDepositAmount) {\\n revert LessThanMinDeposit(assets, minimumDepositAmount);\\n }\\n\\n return super.deposit(assets, receiver);\\n }\\n\\n /// @notice Mints shares to receiver by depositing tBTC tokens.\\n /// @dev Takes into account a deposit parameter, minimum deposit amount,\\n /// which determines the minimum amount for a single deposit operation.\\n /// The amount of the assets has to be pre-approved in the tBTC\\n /// contract.\\n /// The msg.sender is required to grant approval for tBTC transfer.\\n /// To determine the total assets amount necessary for approval\\n /// corresponding to a given share amount, use the `previewMint` function.\\n /// @param shares Amount of shares to mint.\\n /// @param receiver The address to which the shares will be minted.\\n function mint(\\n uint256 shares,\\n address receiver\\n ) public override returns (uint256 assets) {\\n if ((assets = super.mint(shares, receiver)) < minimumDepositAmount) {\\n revert LessThanMinDeposit(assets, minimumDepositAmount);\\n }\\n }\\n\\n /// @notice Returns value of assets that would be exchanged for the amount of\\n /// shares owned by the `account`.\\n /// @param account Owner of shares.\\n /// @return Assets amount.\\n function assetsBalanceOf(address account) public view returns (uint256) {\\n return convertToAssets(balanceOf(account));\\n }\\n\\n /// @notice Returns the maximum amount of the tBTC token that can be\\n /// deposited into the vault for the receiver through a deposit\\n /// call. It takes into account the deposit parameter, maximum total\\n /// assets, which determines the total amount of tBTC token held by\\n /// Acre protocol.\\n /// @dev When the remaining amount of unused limit is less than the minimum\\n /// deposit amount, this function returns 0.\\n /// @return The maximum amount of tBTC token that can be deposited into\\n /// Acre protocol for the receiver.\\n function maxDeposit(address) public view override returns (uint256) {\\n if (maximumTotalAssets == type(uint256).max) {\\n return type(uint256).max;\\n }\\n\\n uint256 _totalAssets = totalAssets();\\n\\n return\\n _totalAssets >= maximumTotalAssets\\n ? 0\\n : maximumTotalAssets - _totalAssets;\\n }\\n\\n /// @notice Returns the maximum amount of the vault shares that can be\\n /// minted for the receiver, through a mint call.\\n /// @dev Since the stBTC contract limits the maximum total tBTC tokens this\\n /// function converts the maximum deposit amount to shares.\\n /// @return The maximum amount of the vault shares.\\n function maxMint(address receiver) public view override returns (uint256) {\\n uint256 _maxDeposit = maxDeposit(receiver);\\n\\n // slither-disable-next-line incorrect-equality\\n return\\n _maxDeposit == type(uint256).max\\n ? type(uint256).max\\n : convertToShares(_maxDeposit);\\n }\\n\\n /// @return Returns deposit parameters.\\n function depositParameters() public view returns (uint256, uint256) {\\n return (minimumDepositAmount, maximumTotalAssets);\\n }\\n}\\n\",\"keccak256\":\"0x8fa5224df372d53f1d86ee41132cb614d45916ba0b715b967d8d308b67a2a855\",\"license\":\"GPL-3.0-only\"}},\"version\":1}", - "bytecode": "0x60c06040523480156200001157600080fd5b506040516200221a3803806200221a8339810160408190526200003491620002d5565b33826040518060400160405280601381526020017f41637265205374616b656420426974636f696e0000000000000000000000000081525060405180604001604052806005815260200164737442544360d81b81525081600390816200009b9190620003b9565b506004620000aa8282620003b9565b505050600080620000c1836200018560201b60201c565b9150915081620000d3576012620000d5565b805b60ff1660a05250506001600160a01b0390811660805281166200011257604051631e4fbdf760e01b81526000600482015260240160405180910390fd5b6200011d816200026a565b506001600160a01b038116620001465760405163d92e233d60e01b815260040160405180910390fd5b600780546001600160a01b0319166001600160a01b03929092169190911790555066038d7ea4c6800060085568015af1d78b58c40000600955620004d0565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290516000918291829182916001600160a01b03871691620001ce9162000485565b600060405180830381855afa9150503d80600081146200020b576040519150601f19603f3d011682016040523d82523d6000602084013e62000210565b606091505b50915091508180156200022557506020815110155b156200025d57600081806020019051810190620002439190620004b6565b905060ff81116200025b576001969095509350505050565b505b5060009485945092505050565b600580546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6001600160a01b0381168114620002d257600080fd5b50565b60008060408385031215620002e957600080fd5b8251620002f681620002bc565b60208401519092506200030981620002bc565b809150509250929050565b634e487b7160e01b600052604160045260246000fd5b600181811c908216806200033f57607f821691505b6020821081036200036057634e487b7160e01b600052602260045260246000fd5b50919050565b601f821115620003b457600081815260208120601f850160051c810160208610156200038f5750805b601f850160051c820191505b81811015620003b0578281556001016200039b565b5050505b505050565b81516001600160401b03811115620003d557620003d562000314565b620003ed81620003e684546200032a565b8462000366565b602080601f8311600181146200042557600084156200040c5750858301515b600019600386901b1c1916600185901b178555620003b0565b600085815260208120601f198616915b82811015620004565788860151825594840194600190910190840162000435565b5085821015620004755787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b6000825160005b81811015620004a857602081860181015185830152016200048c565b506000920191825250919050565b600060208284031215620004c957600080fd5b5051919050565b60805160a051611d0162000519600039600061070d0152600081816103350152818161059d0152818161082c01528181610871015281816110b501526114ff0152611d016000f3fe608060405234801561001057600080fd5b50600436106102775760003560e01c80637f51bb1f11610160578063c42b64d0116100d8578063d905777e1161008c578063e9c092e311610071578063e9c092e314610546578063ef8b30f7146104c1578063f2fde38b1461055957600080fd5b8063d905777e146104fa578063dd62ed3e1461050d57600080fd5b8063c6e6f592116100bd578063c6e6f592146104c1578063cb7e9057146104d4578063ce96cb77146104e757600080fd5b8063c42b64d014610493578063c63d75b6146104ae57600080fd5b8063995bd0c11161012f578063b3d7f6b911610114578063b3d7f6b91461045a578063b460af941461046d578063ba0876521461048057600080fd5b8063995bd0c114610434578063a9059cbb1461044757600080fd5b80637f51bb1f146103f55780638da5cb5b1461040857806394bf804d1461041957806395d89b411461042c57600080fd5b806338d52e0f116101f3578063543bda75116101c25780636e553f65116101a75780636e553f65146103b157806370a08231146103c4578063715018a6146103ed57600080fd5b8063543bda751461039557806361d027b31461039e57600080fd5b806338d52e0f14610333578063402d267d1461036d57806342af1198146103805780634cdad506146102ac57600080fd5b8063095ea7b31161024a57806318160ddd1161022f57806318160ddd146102fe57806323b872dd14610306578063313ce5671461031957600080fd5b8063095ea7b3146102c85780630a28a477146102eb57600080fd5b806301e1d1141461027c57806306fdde031461029757806307a2d13a146102ac578063080c279a146102bf575b600080fd5b61028461056c565b6040519081526020015b60405180910390f35b61029f610615565b60405161028e91906118e9565b6102846102ba36600461191c565b6106a7565b61028460085481565b6102db6102d636600461194a565b6106ba565b604051901515815260200161028e565b6102846102f936600461191c565b6106d2565b600254610284565b6102db610314366004611976565b6106df565b610321610705565b60405160ff909116815260200161028e565b7f00000000000000000000000000000000000000000000000000000000000000005b6040516001600160a01b03909116815260200161028e565b61028461037b3660046119b7565b610731565b61039361038e3660046119b7565b610779565b005b61028460095481565b600754610355906001600160a01b031681565b6102846103bf3660046119d4565b610899565b6102846103d23660046119b7565b6001600160a01b031660009081526020819052604090205490565b6103936108df565b6103936104033660046119b7565b6108f3565b6005546001600160a01b0316610355565b6102846104273660046119d4565b6109c5565b61029f610a04565b6102846104423660046119b7565b610a13565b6102db61045536600461194a565b610a35565b61028461046836600461191c565b610a43565b61028461047b366004611a04565b610a50565b61028461048e366004611a04565b610ad4565b6008546009546040805192835260208301919091520161028e565b6102846104bc3660046119b7565b610b4f565b6102846104cf36600461191c565b610b79565b600654610355906001600160a01b031681565b6102846104f53660046119b7565b610b86565b6102846105083660046119b7565b610baa565b61028461051b366004611a46565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b610393610554366004611a74565b610bc8565b6103936105673660046119b7565b610c17565b6040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa1580156105ec573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106109190611a96565b905090565b60606003805461062490611aaf565b80601f016020809104026020016040519081016040528092919081815260200182805461065090611aaf565b801561069d5780601f106106725761010080835404028352916020019161069d565b820191906000526020600020905b81548152906001019060200180831161068057829003601f168201915b5050505050905090565b60006106b4826000610c6e565b92915050565b6000336106c8818585610ca8565b5060019392505050565b60006106b4826001610cba565b6000336106ed858285610cea565b6106f8858585610d81565b60019150505b9392505050565b6000610610817f0000000000000000000000000000000000000000000000000000000000000000611aff565b6000600019600954036107475750600019919050565b600061075161056c565b9050600954811015610770578060095461076b9190611b18565b6106fe565b60009392505050565b610781610de0565b6001600160a01b0381166107a85760405163d92e233d60e01b815260040160405180910390fd5b600654604080516001600160a01b0392831680825292841660208201527ff6e490308a0c67484cf1082cb89a68053c7a7bbf474247e8b634957e2ce2f296910160405180910390a16006805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b038481169190911790915581161561085c5761085c8160007f00000000000000000000000000000000000000000000000000000000000000005b6001600160a01b03169190610e26565b600654610895906001600160a01b03166000197f000000000000000000000000000000000000000000000000000000000000000061084c565b5050565b60006008548310156108d5576008546040516314d6e77b60e31b81526108cc918591600401918252602082015260400190565b60405180910390fd5b6106fe8383610f27565b6108e7610de0565b6108f16000610fa9565b565b6108fb610de0565b6001600160a01b0381166109225760405163d92e233d60e01b815260040160405180910390fd5b306001600160a01b03821603610964576040517f593230f700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6007805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0383169081179091556040519081527f7dae230f18360d76a040c81f050aa14eb9d6dc7901b20fc5d855e2a20fe814d19060200160405180910390a150565b60006008546109d48484611008565b91508110156106b4576008546040516314d6e77b60e31b81526108cc918391600401918252602082015260400190565b60606004805461062490611aaf565b6001600160a01b0381166000908152602081905260408120546106b4906106a7565b6000336106c8818585610d81565b60006106b4826001610c6e565b600080610a5c83610b86565b905080851115610ab1576040517ffe9cceec0000000000000000000000000000000000000000000000000000000081526001600160a01b038416600482015260248101869052604481018290526064016108cc565b6000610abc866106d2565b9050610acb3386868985611082565b95945050505050565b600080610ae083610baa565b905080851115610b35576040517fb94abeec0000000000000000000000000000000000000000000000000000000081526001600160a01b038416600482015260248101869052604481018290526064016108cc565b6000610b40866106a7565b9050610acb338686848a611082565b600080610b5b83610731565b90506000198114610b6f5761076b81610b79565b6000199392505050565b60006106b4826000610cba565b6001600160a01b0381166000908152602081905260408120546106b4906000610c6e565b6001600160a01b0381166000908152602081905260408120546106b4565b610bd0610de0565b6008829055600981905560408051838152602081018390527f5543b97d9277fef57d70edac6c4c10f4426957b886dfe97286c01d2218a53280910160405180910390a15050565b610c1f610de0565b6001600160a01b038116610c62576040517f1e4fbdf7000000000000000000000000000000000000000000000000000000008152600060048201526024016108cc565b610c6b81610fa9565b50565b60006106fe610c7b61056c565b610c86906001611b2b565b610c926000600a611c22565b600254610c9f9190611b2b565b85919085611142565b610cb58383836001611191565b505050565b60006106fe610cca82600a611c22565b600254610cd79190611b2b565b610cdf61056c565b610c9f906001611b2b565b6001600160a01b038381166000908152600160209081526040808320938616835292905220546000198114610d7b5781811015610d6c576040517ffb8f41b20000000000000000000000000000000000000000000000000000000081526001600160a01b038416600482015260248101829052604481018390526064016108cc565b610d7b84848484036000611191565b50505050565b6001600160a01b038316610dab57604051634b637e8f60e11b8152600060048201526024016108cc565b6001600160a01b038216610dd55760405163ec442f0560e01b8152600060048201526024016108cc565b610cb5838383611298565b6005546001600160a01b031633146108f1576040517f118cdaa70000000000000000000000000000000000000000000000000000000081523360048201526024016108cc565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f095ea7b300000000000000000000000000000000000000000000000000000000179052610ea584826113db565b610d7b576040516001600160a01b03848116602483015260006044830152610f1d91869182169063095ea7b3906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505061147e565b610d7b848261147e565b600080610f3383610731565b905080841115610f88576040517f79012fb20000000000000000000000000000000000000000000000000000000081526001600160a01b038416600482015260248101859052604481018290526064016108cc565b6000610f9385610b79565b9050610fa1338587846114fa565b949350505050565b600580546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b60008061101483610b4f565b905080841115611069576040517f284ff6670000000000000000000000000000000000000000000000000000000081526001600160a01b038416600482015260248101859052604481018290526064016108cc565b600061107485610a43565b9050610fa1338583886114fa565b826001600160a01b0316856001600160a01b0316146110a6576110a6838683610cea565b6110b0838261157e565b6110db7f000000000000000000000000000000000000000000000000000000000000000085846115b4565b826001600160a01b0316846001600160a01b0316866001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8585604051611133929190918252602082015260400190565b60405180910390a45050505050565b6000806111508686866115e5565b905061115b836116c2565b801561117757506000848061117257611172611c31565b868809115b15610acb57611187600182611b2b565b9695505050505050565b6001600160a01b0384166111d4576040517fe602df05000000000000000000000000000000000000000000000000000000008152600060048201526024016108cc565b6001600160a01b038316611217576040517f94280d62000000000000000000000000000000000000000000000000000000008152600060048201526024016108cc565b6001600160a01b0380851660009081526001602090815260408083209387168352929052208290558015610d7b57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258460405161128a91815260200190565b60405180910390a350505050565b6001600160a01b0383166112c35780600260008282546112b89190611b2b565b9091555061134e9050565b6001600160a01b0383166000908152602081905260409020548181101561132f576040517fe450d38c0000000000000000000000000000000000000000000000000000000081526001600160a01b038516600482015260248101829052604481018390526064016108cc565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b03821661136a57600280548290039055611389565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040516113ce91815260200190565b60405180910390a3505050565b6000806000846001600160a01b0316846040516113f89190611c47565b6000604051808303816000865af19150503d8060008114611435576040519150601f19603f3d011682016040523d82523d6000602084013e61143a565b606091505b50915091508180156114645750805115806114645750808060200190518101906114649190611c63565b8015610acb5750505050506001600160a01b03163b151590565b60006114936001600160a01b038416836116ef565b905080516000141580156114b85750808060200190518101906114b69190611c63565b155b15610cb5576040517f5274afe70000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024016108cc565b6115267f00000000000000000000000000000000000000000000000000000000000000008530856116fd565b6115308382611736565b826001600160a01b0316846001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7848460405161128a929190918252602082015260400190565b6001600160a01b0382166115a857604051634b637e8f60e11b8152600060048201526024016108cc565b61089582600083611298565b6040516001600160a01b03838116602483015260448201839052610cb591859182169063a9059cbb90606401610ed6565b600083830281600019858709828110838203039150508060000361161c5783828161161257611612611c31565b04925050506106fe565b808411611655576040517f227bc15300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b600060028260038111156116d8576116d8611c85565b6116e29190611c9b565b60ff166001149050919050565b60606106fe8383600061176c565b6040516001600160a01b038481166024830152838116604483015260648201839052610d7b9186918216906323b872dd90608401610ed6565b6001600160a01b0382166117605760405163ec442f0560e01b8152600060048201526024016108cc565b61089560008383611298565b6060814710156117aa576040517fcd7860590000000000000000000000000000000000000000000000000000000081523060048201526024016108cc565b600080856001600160a01b031684866040516117c69190611c47565b60006040518083038185875af1925050503d8060008114611803576040519150601f19603f3d011682016040523d82523d6000602084013e611808565b606091505b50915091506111878683836060826118235761076b82611883565b815115801561183a57506001600160a01b0384163b155b1561187c576040517f9996b3150000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024016108cc565b50806106fe565b8051156118935780518082602001fd5b6040517f1425ea4200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60005b838110156118e05781810151838201526020016118c8565b50506000910152565b60208152600082518060208401526119088160408501602087016118c5565b601f01601f19169190910160400192915050565b60006020828403121561192e57600080fd5b5035919050565b6001600160a01b0381168114610c6b57600080fd5b6000806040838503121561195d57600080fd5b823561196881611935565b946020939093013593505050565b60008060006060848603121561198b57600080fd5b833561199681611935565b925060208401356119a681611935565b929592945050506040919091013590565b6000602082840312156119c957600080fd5b81356106fe81611935565b600080604083850312156119e757600080fd5b8235915060208301356119f981611935565b809150509250929050565b600080600060608486031215611a1957600080fd5b833592506020840135611a2b81611935565b91506040840135611a3b81611935565b809150509250925092565b60008060408385031215611a5957600080fd5b8235611a6481611935565b915060208301356119f981611935565b60008060408385031215611a8757600080fd5b50508035926020909101359150565b600060208284031215611aa857600080fd5b5051919050565b600181811c90821680611ac357607f821691505b602082108103611ae357634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b60ff81811683821601908111156106b4576106b4611ae9565b818103818111156106b4576106b4611ae9565b808201808211156106b4576106b4611ae9565b600181815b80851115611b79578160001904821115611b5f57611b5f611ae9565b80851615611b6c57918102915b93841c9390800290611b43565b509250929050565b600082611b90575060016106b4565b81611b9d575060006106b4565b8160018114611bb35760028114611bbd57611bd9565b60019150506106b4565b60ff841115611bce57611bce611ae9565b50506001821b6106b4565b5060208310610133831016604e8410600b8410161715611bfc575081810a6106b4565b611c068383611b3e565b8060001904821115611c1a57611c1a611ae9565b029392505050565b60006106fe60ff841683611b81565b634e487b7160e01b600052601260045260246000fd5b60008251611c598184602087016118c5565b9190910192915050565b600060208284031215611c7557600080fd5b815180151581146106fe57600080fd5b634e487b7160e01b600052602160045260246000fd5b600060ff831680611cbc57634e487b7160e01b600052601260045260246000fd5b8060ff8416069150509291505056fea2646970667358221220613e87e5d7e469eae628fc2f45b68eaf8d314fc3fbd6b5de50baf2a5e5c5a97664736f6c63430008150033", - "deployedBytecode": "0x608060405234801561001057600080fd5b50600436106102775760003560e01c80637f51bb1f11610160578063c42b64d0116100d8578063d905777e1161008c578063e9c092e311610071578063e9c092e314610546578063ef8b30f7146104c1578063f2fde38b1461055957600080fd5b8063d905777e146104fa578063dd62ed3e1461050d57600080fd5b8063c6e6f592116100bd578063c6e6f592146104c1578063cb7e9057146104d4578063ce96cb77146104e757600080fd5b8063c42b64d014610493578063c63d75b6146104ae57600080fd5b8063995bd0c11161012f578063b3d7f6b911610114578063b3d7f6b91461045a578063b460af941461046d578063ba0876521461048057600080fd5b8063995bd0c114610434578063a9059cbb1461044757600080fd5b80637f51bb1f146103f55780638da5cb5b1461040857806394bf804d1461041957806395d89b411461042c57600080fd5b806338d52e0f116101f3578063543bda75116101c25780636e553f65116101a75780636e553f65146103b157806370a08231146103c4578063715018a6146103ed57600080fd5b8063543bda751461039557806361d027b31461039e57600080fd5b806338d52e0f14610333578063402d267d1461036d57806342af1198146103805780634cdad506146102ac57600080fd5b8063095ea7b31161024a57806318160ddd1161022f57806318160ddd146102fe57806323b872dd14610306578063313ce5671461031957600080fd5b8063095ea7b3146102c85780630a28a477146102eb57600080fd5b806301e1d1141461027c57806306fdde031461029757806307a2d13a146102ac578063080c279a146102bf575b600080fd5b61028461056c565b6040519081526020015b60405180910390f35b61029f610615565b60405161028e91906118e9565b6102846102ba36600461191c565b6106a7565b61028460085481565b6102db6102d636600461194a565b6106ba565b604051901515815260200161028e565b6102846102f936600461191c565b6106d2565b600254610284565b6102db610314366004611976565b6106df565b610321610705565b60405160ff909116815260200161028e565b7f00000000000000000000000000000000000000000000000000000000000000005b6040516001600160a01b03909116815260200161028e565b61028461037b3660046119b7565b610731565b61039361038e3660046119b7565b610779565b005b61028460095481565b600754610355906001600160a01b031681565b6102846103bf3660046119d4565b610899565b6102846103d23660046119b7565b6001600160a01b031660009081526020819052604090205490565b6103936108df565b6103936104033660046119b7565b6108f3565b6005546001600160a01b0316610355565b6102846104273660046119d4565b6109c5565b61029f610a04565b6102846104423660046119b7565b610a13565b6102db61045536600461194a565b610a35565b61028461046836600461191c565b610a43565b61028461047b366004611a04565b610a50565b61028461048e366004611a04565b610ad4565b6008546009546040805192835260208301919091520161028e565b6102846104bc3660046119b7565b610b4f565b6102846104cf36600461191c565b610b79565b600654610355906001600160a01b031681565b6102846104f53660046119b7565b610b86565b6102846105083660046119b7565b610baa565b61028461051b366004611a46565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b610393610554366004611a74565b610bc8565b6103936105673660046119b7565b610c17565b6040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa1580156105ec573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106109190611a96565b905090565b60606003805461062490611aaf565b80601f016020809104026020016040519081016040528092919081815260200182805461065090611aaf565b801561069d5780601f106106725761010080835404028352916020019161069d565b820191906000526020600020905b81548152906001019060200180831161068057829003601f168201915b5050505050905090565b60006106b4826000610c6e565b92915050565b6000336106c8818585610ca8565b5060019392505050565b60006106b4826001610cba565b6000336106ed858285610cea565b6106f8858585610d81565b60019150505b9392505050565b6000610610817f0000000000000000000000000000000000000000000000000000000000000000611aff565b6000600019600954036107475750600019919050565b600061075161056c565b9050600954811015610770578060095461076b9190611b18565b6106fe565b60009392505050565b610781610de0565b6001600160a01b0381166107a85760405163d92e233d60e01b815260040160405180910390fd5b600654604080516001600160a01b0392831680825292841660208201527ff6e490308a0c67484cf1082cb89a68053c7a7bbf474247e8b634957e2ce2f296910160405180910390a16006805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b038481169190911790915581161561085c5761085c8160007f00000000000000000000000000000000000000000000000000000000000000005b6001600160a01b03169190610e26565b600654610895906001600160a01b03166000197f000000000000000000000000000000000000000000000000000000000000000061084c565b5050565b60006008548310156108d5576008546040516314d6e77b60e31b81526108cc918591600401918252602082015260400190565b60405180910390fd5b6106fe8383610f27565b6108e7610de0565b6108f16000610fa9565b565b6108fb610de0565b6001600160a01b0381166109225760405163d92e233d60e01b815260040160405180910390fd5b306001600160a01b03821603610964576040517f593230f700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6007805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0383169081179091556040519081527f7dae230f18360d76a040c81f050aa14eb9d6dc7901b20fc5d855e2a20fe814d19060200160405180910390a150565b60006008546109d48484611008565b91508110156106b4576008546040516314d6e77b60e31b81526108cc918391600401918252602082015260400190565b60606004805461062490611aaf565b6001600160a01b0381166000908152602081905260408120546106b4906106a7565b6000336106c8818585610d81565b60006106b4826001610c6e565b600080610a5c83610b86565b905080851115610ab1576040517ffe9cceec0000000000000000000000000000000000000000000000000000000081526001600160a01b038416600482015260248101869052604481018290526064016108cc565b6000610abc866106d2565b9050610acb3386868985611082565b95945050505050565b600080610ae083610baa565b905080851115610b35576040517fb94abeec0000000000000000000000000000000000000000000000000000000081526001600160a01b038416600482015260248101869052604481018290526064016108cc565b6000610b40866106a7565b9050610acb338686848a611082565b600080610b5b83610731565b90506000198114610b6f5761076b81610b79565b6000199392505050565b60006106b4826000610cba565b6001600160a01b0381166000908152602081905260408120546106b4906000610c6e565b6001600160a01b0381166000908152602081905260408120546106b4565b610bd0610de0565b6008829055600981905560408051838152602081018390527f5543b97d9277fef57d70edac6c4c10f4426957b886dfe97286c01d2218a53280910160405180910390a15050565b610c1f610de0565b6001600160a01b038116610c62576040517f1e4fbdf7000000000000000000000000000000000000000000000000000000008152600060048201526024016108cc565b610c6b81610fa9565b50565b60006106fe610c7b61056c565b610c86906001611b2b565b610c926000600a611c22565b600254610c9f9190611b2b565b85919085611142565b610cb58383836001611191565b505050565b60006106fe610cca82600a611c22565b600254610cd79190611b2b565b610cdf61056c565b610c9f906001611b2b565b6001600160a01b038381166000908152600160209081526040808320938616835292905220546000198114610d7b5781811015610d6c576040517ffb8f41b20000000000000000000000000000000000000000000000000000000081526001600160a01b038416600482015260248101829052604481018390526064016108cc565b610d7b84848484036000611191565b50505050565b6001600160a01b038316610dab57604051634b637e8f60e11b8152600060048201526024016108cc565b6001600160a01b038216610dd55760405163ec442f0560e01b8152600060048201526024016108cc565b610cb5838383611298565b6005546001600160a01b031633146108f1576040517f118cdaa70000000000000000000000000000000000000000000000000000000081523360048201526024016108cc565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f095ea7b300000000000000000000000000000000000000000000000000000000179052610ea584826113db565b610d7b576040516001600160a01b03848116602483015260006044830152610f1d91869182169063095ea7b3906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505061147e565b610d7b848261147e565b600080610f3383610731565b905080841115610f88576040517f79012fb20000000000000000000000000000000000000000000000000000000081526001600160a01b038416600482015260248101859052604481018290526064016108cc565b6000610f9385610b79565b9050610fa1338587846114fa565b949350505050565b600580546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b60008061101483610b4f565b905080841115611069576040517f284ff6670000000000000000000000000000000000000000000000000000000081526001600160a01b038416600482015260248101859052604481018290526064016108cc565b600061107485610a43565b9050610fa1338583886114fa565b826001600160a01b0316856001600160a01b0316146110a6576110a6838683610cea565b6110b0838261157e565b6110db7f000000000000000000000000000000000000000000000000000000000000000085846115b4565b826001600160a01b0316846001600160a01b0316866001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8585604051611133929190918252602082015260400190565b60405180910390a45050505050565b6000806111508686866115e5565b905061115b836116c2565b801561117757506000848061117257611172611c31565b868809115b15610acb57611187600182611b2b565b9695505050505050565b6001600160a01b0384166111d4576040517fe602df05000000000000000000000000000000000000000000000000000000008152600060048201526024016108cc565b6001600160a01b038316611217576040517f94280d62000000000000000000000000000000000000000000000000000000008152600060048201526024016108cc565b6001600160a01b0380851660009081526001602090815260408083209387168352929052208290558015610d7b57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258460405161128a91815260200190565b60405180910390a350505050565b6001600160a01b0383166112c35780600260008282546112b89190611b2b565b9091555061134e9050565b6001600160a01b0383166000908152602081905260409020548181101561132f576040517fe450d38c0000000000000000000000000000000000000000000000000000000081526001600160a01b038516600482015260248101829052604481018390526064016108cc565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b03821661136a57600280548290039055611389565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040516113ce91815260200190565b60405180910390a3505050565b6000806000846001600160a01b0316846040516113f89190611c47565b6000604051808303816000865af19150503d8060008114611435576040519150601f19603f3d011682016040523d82523d6000602084013e61143a565b606091505b50915091508180156114645750805115806114645750808060200190518101906114649190611c63565b8015610acb5750505050506001600160a01b03163b151590565b60006114936001600160a01b038416836116ef565b905080516000141580156114b85750808060200190518101906114b69190611c63565b155b15610cb5576040517f5274afe70000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024016108cc565b6115267f00000000000000000000000000000000000000000000000000000000000000008530856116fd565b6115308382611736565b826001600160a01b0316846001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7848460405161128a929190918252602082015260400190565b6001600160a01b0382166115a857604051634b637e8f60e11b8152600060048201526024016108cc565b61089582600083611298565b6040516001600160a01b03838116602483015260448201839052610cb591859182169063a9059cbb90606401610ed6565b600083830281600019858709828110838203039150508060000361161c5783828161161257611612611c31565b04925050506106fe565b808411611655576040517f227bc15300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b600060028260038111156116d8576116d8611c85565b6116e29190611c9b565b60ff166001149050919050565b60606106fe8383600061176c565b6040516001600160a01b038481166024830152838116604483015260648201839052610d7b9186918216906323b872dd90608401610ed6565b6001600160a01b0382166117605760405163ec442f0560e01b8152600060048201526024016108cc565b61089560008383611298565b6060814710156117aa576040517fcd7860590000000000000000000000000000000000000000000000000000000081523060048201526024016108cc565b600080856001600160a01b031684866040516117c69190611c47565b60006040518083038185875af1925050503d8060008114611803576040519150601f19603f3d011682016040523d82523d6000602084013e611808565b606091505b50915091506111878683836060826118235761076b82611883565b815115801561183a57506001600160a01b0384163b155b1561187c576040517f9996b3150000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024016108cc565b50806106fe565b8051156118935780518082602001fd5b6040517f1425ea4200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60005b838110156118e05781810151838201526020016118c8565b50506000910152565b60208152600082518060208401526119088160408501602087016118c5565b601f01601f19169190910160400192915050565b60006020828403121561192e57600080fd5b5035919050565b6001600160a01b0381168114610c6b57600080fd5b6000806040838503121561195d57600080fd5b823561196881611935565b946020939093013593505050565b60008060006060848603121561198b57600080fd5b833561199681611935565b925060208401356119a681611935565b929592945050506040919091013590565b6000602082840312156119c957600080fd5b81356106fe81611935565b600080604083850312156119e757600080fd5b8235915060208301356119f981611935565b809150509250929050565b600080600060608486031215611a1957600080fd5b833592506020840135611a2b81611935565b91506040840135611a3b81611935565b809150509250925092565b60008060408385031215611a5957600080fd5b8235611a6481611935565b915060208301356119f981611935565b60008060408385031215611a8757600080fd5b50508035926020909101359150565b600060208284031215611aa857600080fd5b5051919050565b600181811c90821680611ac357607f821691505b602082108103611ae357634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b60ff81811683821601908111156106b4576106b4611ae9565b818103818111156106b4576106b4611ae9565b808201808211156106b4576106b4611ae9565b600181815b80851115611b79578160001904821115611b5f57611b5f611ae9565b80851615611b6c57918102915b93841c9390800290611b43565b509250929050565b600082611b90575060016106b4565b81611b9d575060006106b4565b8160018114611bb35760028114611bbd57611bd9565b60019150506106b4565b60ff841115611bce57611bce611ae9565b50506001821b6106b4565b5060208310610133831016604e8410600b8410161715611bfc575081810a6106b4565b611c068383611b3e565b8060001904821115611c1a57611c1a611ae9565b029392505050565b60006106fe60ff841683611b81565b634e487b7160e01b600052601260045260246000fd5b60008251611c598184602087016118c5565b9190910192915050565b600060208284031215611c7557600080fd5b815180151581146106fe57600080fd5b634e487b7160e01b600052602160045260246000fd5b600060ff831680611cbc57634e487b7160e01b600052601260045260246000fd5b8060ff8416069150509291505056fea2646970667358221220613e87e5d7e469eae628fc2f45b68eaf8d314fc3fbd6b5de50baf2a5e5c5a97664736f6c63430008150033", - "devdoc": { - "details": "ERC-4626 is a standard to optimize and unify the technical parameters of yield-bearing vaults. This contract facilitates the minting and burning of shares (stBTC), which are represented as standard ERC20 tokens, providing a seamless exchange with tBTC tokens.", - "errors": { - "AddressEmptyCode(address)": [ - { - "details": "There's no code at `target` (it is not a contract)." - } - ], - "AddressInsufficientBalance(address)": [ - { - "details": "The ETH balance of the account is not enough to perform the operation." - } - ], - "ERC20InsufficientAllowance(address,uint256,uint256)": [ - { - "details": "Indicates a failure with the `spender`’s `allowance`. Used in transfers.", - "params": { - "allowance": "Amount of tokens a `spender` is allowed to operate with.", - "needed": "Minimum amount required to perform a transfer.", - "spender": "Address that may be allowed to operate on tokens without being their owner." - } - } - ], - "ERC20InsufficientBalance(address,uint256,uint256)": [ - { - "details": "Indicates an error related to the current `balance` of a `sender`. Used in transfers.", - "params": { - "balance": "Current balance for the interacting account.", - "needed": "Minimum amount required to perform a transfer.", - "sender": "Address whose tokens are being transferred." - } - } - ], - "ERC20InvalidApprover(address)": [ - { - "details": "Indicates a failure with the `approver` of a token to be approved. Used in approvals.", - "params": { - "approver": "Address initiating an approval operation." - } - } - ], - "ERC20InvalidReceiver(address)": [ - { - "details": "Indicates a failure with the token `receiver`. Used in transfers.", - "params": { - "receiver": "Address to which tokens are being transferred." - } - } - ], - "ERC20InvalidSender(address)": [ - { - "details": "Indicates a failure with the token `sender`. Used in transfers.", - "params": { - "sender": "Address whose tokens are being transferred." - } - } - ], - "ERC20InvalidSpender(address)": [ - { - "details": "Indicates a failure with the `spender` to be approved. Used in approvals.", - "params": { - "spender": "Address that may be allowed to operate on tokens without being their owner." - } - } - ], - "ERC4626ExceededMaxDeposit(address,uint256,uint256)": [ - { - "details": "Attempted to deposit more assets than the max amount for `receiver`." - } - ], - "ERC4626ExceededMaxMint(address,uint256,uint256)": [ - { - "details": "Attempted to mint more shares than the max amount for `receiver`." - } - ], - "ERC4626ExceededMaxRedeem(address,uint256,uint256)": [ - { - "details": "Attempted to redeem more shares than the max amount for `receiver`." - } - ], - "ERC4626ExceededMaxWithdraw(address,uint256,uint256)": [ - { - "details": "Attempted to withdraw more assets than the max amount for `receiver`." - } - ], - "FailedInnerCall()": [ - { - "details": "A call to an address target failed. The target may have reverted." - } - ], - "LessThanMinDeposit(uint256,uint256)": [ - { - "params": { - "amount": "Amount to check.", - "min": "Minimum amount to check 'amount' against." - } - } - ], - "MathOverflowedMulDiv()": [ - { - "details": "Muldiv operation overflow." - } - ], - "OwnableInvalidOwner(address)": [ - { - "details": "The owner is not a valid owner account. (eg. `address(0)`)" - } - ], - "OwnableUnauthorizedAccount(address)": [ - { - "details": "The caller account is not authorized to perform an operation." - } - ], - "SafeERC20FailedOperation(address)": [ - { - "details": "An operation with an ERC20 token failed." - } - ] - }, - "events": { - "Approval(address,address,uint256)": { - "details": "Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance." - }, - "DepositParametersUpdated(uint256,uint256)": { - "params": { - "maximumTotalAssets": "New value of the maximum total assets amount.", - "minimumDepositAmount": "New value of the minimum deposit amount." - } - }, - "DispatcherUpdated(address,address)": { - "params": { - "newDispatcher": "Address of the new dispatcher contract.", - "oldDispatcher": "Address of the old dispatcher contract." - } - }, - "Transfer(address,address,uint256)": { - "details": "Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero." - }, - "TreasuryUpdated(address)": { - "params": { - "treasury": "New treasury wallet address." - } - } - }, - "kind": "dev", - "methods": { - "allowance(address,address)": { - "details": "See {IERC20-allowance}." - }, - "approve(address,uint256)": { - "details": "See {IERC20-approve}. NOTE: If `value` is the maximum `uint256`, the allowance is not updated on `transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address." - }, - "asset()": { - "details": "See {IERC4626-asset}. " - }, - "assetsBalanceOf(address)": { - "params": { - "account": "Owner of shares." - }, - "returns": { - "_0": "Assets amount." - } - }, - "balanceOf(address)": { - "details": "See {IERC20-balanceOf}." - }, - "convertToAssets(uint256)": { - "details": "See {IERC4626-convertToAssets}. " - }, - "convertToShares(uint256)": { - "details": "See {IERC4626-convertToShares}. " - }, - "decimals()": { - "details": "Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This \"original\" value is cached during construction of the vault contract. If this read operation fails (e.g., the asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals. See {IERC20Metadata-decimals}." - }, - "deposit(uint256,address)": { - "details": "Takes into account a deposit parameter, minimum deposit amount, which determines the minimum amount for a single deposit operation. The amount of the assets has to be pre-approved in the tBTC contract.", - "params": { - "assets": "Approved amount of tBTC tokens to deposit.", - "receiver": "The address to which the shares will be minted." - }, - "returns": { - "_0": "Minted shares." - } - }, - "depositParameters()": { - "returns": { - "_0": "Returns deposit parameters." - } - }, - "maxDeposit(address)": { - "details": "When the remaining amount of unused limit is less than the minimum deposit amount, this function returns 0.", - "returns": { - "_0": "The maximum amount of tBTC token that can be deposited into Acre protocol for the receiver." - } - }, - "maxMint(address)": { - "details": "Since the stBTC contract limits the maximum total tBTC tokens this function converts the maximum deposit amount to shares.", - "returns": { - "_0": "The maximum amount of the vault shares." - } - }, - "maxRedeem(address)": { - "details": "See {IERC4626-maxRedeem}. " - }, - "maxWithdraw(address)": { - "details": "See {IERC4626-maxWithdraw}. " - }, - "mint(uint256,address)": { - "details": "Takes into account a deposit parameter, minimum deposit amount, which determines the minimum amount for a single deposit operation. The amount of the assets has to be pre-approved in the tBTC contract. The msg.sender is required to grant approval for tBTC transfer. To determine the total assets amount necessary for approval corresponding to a given share amount, use the `previewMint` function.", - "params": { - "receiver": "The address to which the shares will be minted.", - "shares": "Amount of shares to mint." - } - }, - "name()": { - "details": "Returns the name of the token." - }, - "owner()": { - "details": "Returns the address of the current owner." - }, - "previewDeposit(uint256)": { - "details": "See {IERC4626-previewDeposit}. " - }, - "previewMint(uint256)": { - "details": "See {IERC4626-previewMint}. " - }, - "previewRedeem(uint256)": { - "details": "See {IERC4626-previewRedeem}. " - }, - "previewWithdraw(uint256)": { - "details": "See {IERC4626-previewWithdraw}. " - }, - "redeem(uint256,address,address)": { - "details": "See {IERC4626-redeem}. " - }, - "renounceOwnership()": { - "details": "Leaves the contract without owner. It will not be possible to call `onlyOwner` functions. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby disabling any functionality that is only available to the owner." - }, - "symbol()": { - "details": "Returns the symbol of the token, usually a shorter version of the name." - }, - "totalAssets()": { - "details": "See {IERC4626-totalAssets}. " - }, - "totalSupply()": { - "details": "See {IERC20-totalSupply}." - }, - "transfer(address,uint256)": { - "details": "See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `value`." - }, - "transferFrom(address,address,uint256)": { - "details": "See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowance is the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address. - `from` must have a balance of at least `value`. - the caller must have allowance for ``from``'s tokens of at least `value`." - }, - "transferOwnership(address)": { - "details": "Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner." - }, - "updateDepositParameters(uint256,uint256)": { - "details": "To disable the limit for deposits, set the maximum total assets to maximum (`type(uint256).max`).", - "params": { - "_maximumTotalAssets": "New value of the maximum total assets amount. It is the maximum amount of the tBTC token that the Acre protocol can hold.", - "_minimumDepositAmount": "New value of the minimum deposit amount. It is the minimum amount for a single deposit operation." - } - }, - "updateDispatcher(address)": { - "params": { - "newDispatcher": "Address of the new dispatcher contract." - } - }, - "updateTreasury(address)": { - "params": { - "newTreasury": "New treasury wallet address." - } - }, - "withdraw(uint256,address,address)": { - "details": "See {IERC4626-withdraw}. " - } - }, - "title": "stBTC", - "version": 1 - }, - "userdoc": { - "errors": { - "DisallowedAddress()": [ - { - "notice": "Reverts if the address is disallowed." - } - ], - "LessThanMinDeposit(uint256,uint256)": [ - { - "notice": "Reverts if the amount is less than the minimum deposit amount." - } - ], - "ZeroAddress()": [ - { - "notice": "Reverts if the address is zero." - } - ] - }, - "events": { - "DepositParametersUpdated(uint256,uint256)": { - "notice": "Emitted when deposit parameters are updated." - }, - "DispatcherUpdated(address,address)": { - "notice": "Emitted when the dispatcher contract is updated." - }, - "TreasuryUpdated(address)": { - "notice": "Emitted when the treasury wallet address is updated." - } - }, - "kind": "user", - "methods": { - "assetsBalanceOf(address)": { - "notice": "Returns value of assets that would be exchanged for the amount of shares owned by the `account`." - }, - "deposit(uint256,address)": { - "notice": "Mints shares to receiver by depositing exactly amount of tBTC tokens." - }, - "dispatcher()": { - "notice": "Dispatcher contract that routes tBTC from stBTC to a given vault and back." - }, - "maxDeposit(address)": { - "notice": "Returns the maximum amount of the tBTC token that can be deposited into the vault for the receiver through a deposit call. It takes into account the deposit parameter, maximum total assets, which determines the total amount of tBTC token held by Acre protocol." - }, - "maxMint(address)": { - "notice": "Returns the maximum amount of the vault shares that can be minted for the receiver, through a mint call." - }, - "maximumTotalAssets()": { - "notice": "Maximum total amount of tBTC token held by Acre protocol." - }, - "minimumDepositAmount()": { - "notice": "Minimum amount for a single deposit operation." - }, - "mint(uint256,address)": { - "notice": "Mints shares to receiver by depositing tBTC tokens." - }, - "treasury()": { - "notice": "Address of the treasury wallet, where fees should be transferred to." - }, - "updateDepositParameters(uint256,uint256)": { - "notice": "Updates deposit parameters." - }, - "updateDispatcher(address)": { - "notice": "Updates the dispatcher contract and gives it an unlimited allowance to transfer staked tBTC." - }, - "updateTreasury(address)": { - "notice": "Updates treasury wallet address." - } - }, - "notice": "This contract implements the ERC-4626 tokenized vault standard. By staking tBTC, users acquire a liquid staking token called stBTC, commonly referred to as \"shares\". The staked tBTC is securely deposited into Acre's vaults, where it generates yield over time. Users have the flexibility to redeem stBTC, enabling them to withdraw their staked tBTC along with the accrued yield.", - "version": 1 - }, - "storageLayout": { - "storage": [ - { - "astId": 3600, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_balances", - "offset": 0, - "slot": "0", - "type": "t_mapping(t_address,t_uint256)" - }, - { - "astId": 3606, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_allowances", - "offset": 0, - "slot": "1", - "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" - }, - { - "astId": 3608, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_totalSupply", - "offset": 0, - "slot": "2", - "type": "t_uint256" - }, - { - "astId": 3610, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_name", - "offset": 0, - "slot": "3", - "type": "t_string_storage" - }, - { - "astId": 3612, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_symbol", - "offset": 0, - "slot": "4", - "type": "t_string_storage" - }, - { - "astId": 3131, - "contract": "contracts/stBTC.sol:stBTC", - "label": "_owner", - "offset": 0, - "slot": "5", - "type": "t_address" - }, - { - "astId": 6958, - "contract": "contracts/stBTC.sol:stBTC", - "label": "dispatcher", - "offset": 0, - "slot": "6", - "type": "t_contract(Dispatcher)6868" - }, - { - "astId": 6961, - "contract": "contracts/stBTC.sol:stBTC", - "label": "treasury", - "offset": 0, - "slot": "7", - "type": "t_address" - }, - { - "astId": 6964, - "contract": "contracts/stBTC.sol:stBTC", - "label": "minimumDepositAmount", - "offset": 0, - "slot": "8", - "type": "t_uint256" - }, - { - "astId": 6967, - "contract": "contracts/stBTC.sol:stBTC", - "label": "maximumTotalAssets", - "offset": 0, - "slot": "9", - "type": "t_uint256" - } - ], - "types": { - "t_address": { - "encoding": "inplace", - "label": "address", - "numberOfBytes": "20" - }, - "t_contract(Dispatcher)6868": { - "encoding": "inplace", - "label": "contract Dispatcher", - "numberOfBytes": "20" - }, - "t_mapping(t_address,t_mapping(t_address,t_uint256))": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => mapping(address => uint256))", - "numberOfBytes": "32", - "value": "t_mapping(t_address,t_uint256)" - }, - "t_mapping(t_address,t_uint256)": { - "encoding": "mapping", - "key": "t_address", - "label": "mapping(address => uint256)", - "numberOfBytes": "32", - "value": "t_uint256" - }, - "t_string_storage": { - "encoding": "bytes", - "label": "string", - "numberOfBytes": "32" - }, - "t_uint256": { - "encoding": "inplace", - "label": "uint256", - "numberOfBytes": "32" - } - } - } -} diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index 680f63808..4d44853ca 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -1,5 +1,7 @@ import { packRevealDepositParameters } from "@keep-network/tbtc-v2.ts" import { BitcoinDepositor as BitcoinDepositorTypechain } from "@acre-btc/contracts/typechain/contracts/BitcoinDepositor" +import SepoliaBitcoinDepositor from "@acre-btc/contracts/deployments/sepolia/BitcoinDepositor.json" + import { ZeroAddress, dataSlice, @@ -24,8 +26,6 @@ import { import { Hex } from "../utils" import { EthereumNetwork } from "./network" -import SepoliaBitcoinDepositor from "./artifacts/sepolia/BitcoinDepositor.json" - /** * Ethereum implementation of the BitcoinDepositor. */ diff --git a/sdk/src/lib/ethereum/stbtc.ts b/sdk/src/lib/ethereum/stbtc.ts index 4d3b04e60..d4d44610c 100644 --- a/sdk/src/lib/ethereum/stbtc.ts +++ b/sdk/src/lib/ethereum/stbtc.ts @@ -1,5 +1,6 @@ import { StBTC as StBTCTypechain } from "@acre-btc/contracts/typechain/contracts/StBTC" -import stBTC from "./artifacts/sepolia/stBTC.json" +import stBTC from "@acre-btc/contracts/deployments/sepolia/stBTC.json" + import { EthersContractConfig, EthersContractDeployment, From 611524656672901542cf6fcada3792cd8852964a Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Thu, 11 Apr 2024 18:23:56 +0200 Subject: [PATCH 069/110] Define types for contracts initialization We don't need to import the types for contracts initialization as we can simplify them by removing the deployedAtBlockNumber property which is not used in our SDK code. --- sdk/src/lib/ethereum/contract.ts | 43 ++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/sdk/src/lib/ethereum/contract.ts b/sdk/src/lib/ethereum/contract.ts index 38a4e0905..14c16907f 100644 --- a/sdk/src/lib/ethereum/contract.ts +++ b/sdk/src/lib/ethereum/contract.ts @@ -1,7 +1,3 @@ -import { - EthersContractConfig as _EthersContractConfig, - EthersContractDeployment, -} from "@keep-network/tbtc-v2.ts/dist/src/lib/ethereum/adapter" import { Contract as EthersContract, getAddress, @@ -10,7 +6,20 @@ import { } from "ethers" import { EthereumAddress } from "./address" -export { EthersContractDeployment } +/** + * Contract deployment artifact. + * @see [hardhat-deploy#Deployment](https://github.com/wighawag/hardhat-deploy/blob/0c969e9a27b4eeff9f5ccac7e19721ef2329eed2/types.ts#L358)} + */ +export interface EthersContractDeployment { + /** + * Address of the deployed contract. + */ + address: string + /** + * Contract's ABI. + */ + abi: unknown[] +} /** * Use `VoidSigner` from `ethers` if you want to initialize the Ethereum Acre @@ -21,10 +30,16 @@ export type EthereumSigner = Signer | VoidSigner /** * Represents a config set required to connect an Ethereum contract. */ -export interface EthersContractConfig - // We want to omit the `signerOrProvider` because it points to ethers v5. We - // use ethers v6 in Acre SDK. - extends Omit<_EthersContractConfig, "signerOrProvider"> { +export interface EthersContractConfig { + /** + * Address of the Ethereum contract as a 0x-prefixed hex string. + * Optional parameter, if not provided the value will be resolved from the + * contract artifact. + */ + address?: string + /** + * Signer - will return a Contract which will act on behalf of that signer. The signer will sign all contract transactions. + */ signer: EthereumSigner } @@ -37,13 +52,6 @@ export class EthersContractWrapper { */ protected readonly instance: T - /** - * Number of a block within which the contract was deployed. Value is read - * from the contract deployment artifact. It can be overwritten by setting a - * {@link EthersContractConfig.deployedAtBlockNumber} property. - */ - protected readonly deployedAtBlockNumber: number - /** * Address of this contract instance. */ @@ -61,9 +69,6 @@ export class EthersContractWrapper { ) as T this.#address = contractAddress - - this.deployedAtBlockNumber = - config.deployedAtBlockNumber ?? deployment.receipt.blockNumber } /** From 679374ccf6f9d9476424bf4b25b82f2a41f3d2ac Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Fri, 12 Apr 2024 08:00:50 +0200 Subject: [PATCH 070/110] Use `useMinStakeAmount` instead of a simple selector --- .../ActiveUnstakingStep/UnstakeFormModal/index.tsx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx index 0013e073c..97fe66468 100644 --- a/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx @@ -5,8 +5,7 @@ import { TokenAmountFormValues } from "#/components/shared/TokenAmountForm/Token import { TextMd, TextSm } from "#/components/shared/Typography" import Spinner from "#/components/shared/Spinner" import { FormSubmitButton } from "#/components/shared/Form" -import { useAppSelector } from "#/hooks" -import { selectMinStakeAmount } from "#/store/btc" +import { useMinStakeAmount } from "#/hooks" import UnstakeDetails from "./UnstakeDetails" // TODO: Use a position amount @@ -17,7 +16,7 @@ function UnstakeFormModal({ }: { onSubmitForm: (values: TokenAmountFormValues) => void }) { - const minStakeAmount = useAppSelector(selectMinStakeAmount) + const minStakeAmount = useMinStakeAmount() return ( Date: Fri, 12 Apr 2024 08:56:34 +0200 Subject: [PATCH 071/110] Remove unneeded function declaration after merge --- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index 2ba777b9d..06a220918 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -22,7 +22,6 @@ describe("BitcoinDepositor", () => { const mockedContractInstance = { tbtcVault: jest.fn().mockImplementation(() => vaultAddress.identifierHex), - initializeStake: jest.fn(), initializeDeposit: jest.fn(), minStake: jest.fn().mockImplementation(() => minStakeAmount), } From b6487f1f303940124f76f4377ca3d4a234d8001a Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Fri, 12 Apr 2024 09:15:30 +0200 Subject: [PATCH 072/110] Add .openzeppelin/ to prettierignore --- solidity/.prettierignore | 1 + 1 file changed, 1 insertion(+) diff --git a/solidity/.prettierignore b/solidity/.prettierignore index 567a7eaf1..f44a06c97 100644 --- a/solidity/.prettierignore +++ b/solidity/.prettierignore @@ -1,3 +1,4 @@ +.openzeppelin/ build/ cache/ deployments/ From 9998db0192ab377a1851f71689952e1db7aeec17 Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Fri, 12 Apr 2024 09:52:26 +0200 Subject: [PATCH 073/110] Define DepositState file with default export We want to avoid ignoring the prefer-dfefault-export rule, so we define a dedicated file to DepositState. --- solidity/test/BitcoinDepositor.test.ts | 2 +- solidity/types/depositState.ts | 10 ++++++++++ solidity/types/index.ts | 6 ------ 3 files changed, 11 insertions(+), 7 deletions(-) create mode 100644 solidity/types/depositState.ts delete mode 100644 solidity/types/index.ts diff --git a/solidity/test/BitcoinDepositor.test.ts b/solidity/test/BitcoinDepositor.test.ts index 79b7c82aa..4cfb80283 100644 --- a/solidity/test/BitcoinDepositor.test.ts +++ b/solidity/test/BitcoinDepositor.test.ts @@ -6,7 +6,7 @@ import { expect } from "chai" import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers" import { ContractTransactionResponse, MaxUint256, ZeroAddress } from "ethers" -import { DepositState } from "../types" +import DepositState from "../types/depositState" import type { StBTC, diff --git a/solidity/types/depositState.ts b/solidity/types/depositState.ts new file mode 100644 index 000000000..f9c306c2b --- /dev/null +++ b/solidity/types/depositState.ts @@ -0,0 +1,10 @@ +/** + * Represents the state of a deposit in the BitcoinDepositor contract. + */ +enum DepositState { + Unknown, + Initialized, + Finalized, +} + +export default DepositState diff --git a/solidity/types/index.ts b/solidity/types/index.ts deleted file mode 100644 index 19e2cf0f5..000000000 --- a/solidity/types/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -/* eslint-disable import/prefer-default-export */ -export enum DepositState { - Unknown, - Initialized, - Finalized, -} From f50a49d71dafadcae0260b12c931788af81c6763 Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Fri, 12 Apr 2024 11:22:27 +0200 Subject: [PATCH 074/110] Rename stake to deposit for minimum amount We decided not to call the operation stake in the dapp, so for consistency, we align the naming here. --- .../ActiveStakingStep/StakeFormModal/index.tsx | 8 ++++---- .../ActiveUnstakingStep/UnstakeFormModal/index.tsx | 6 +++--- dapp/src/hooks/sdk/index.ts | 2 +- ...MinStakeAmount.ts => useFetchMinDepositAmount.ts} | 12 ++++++------ dapp/src/hooks/sdk/useFetchSdkData.ts | 4 ++-- dapp/src/hooks/store/index.ts | 2 +- dapp/src/hooks/store/useMinDepositAmount.ts | 6 ++++++ dapp/src/hooks/store/useMinStakeAmount.ts | 6 ------ dapp/src/store/btc/btcSelector.ts | 4 ++-- dapp/src/store/btc/btcSlice.ts | 10 +++++----- sdk/src/lib/contracts/bitcoin-depositor.ts | 4 ++-- sdk/src/lib/ethereum/bitcoin-depositor.ts | 6 +++--- sdk/src/modules/staking/index.ts | 6 +++--- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 12 ++++++------ sdk/test/modules/staking.test.ts | 8 ++++---- sdk/test/utils/mock-acre-contracts.ts | 2 +- 16 files changed, 49 insertions(+), 49 deletions(-) rename dapp/src/hooks/sdk/{useFetchMinStakeAmount.ts => useFetchMinDepositAmount.ts} (55%) create mode 100644 dapp/src/hooks/store/useMinDepositAmount.ts delete mode 100644 dapp/src/hooks/store/useMinStakeAmount.ts diff --git a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx index c6045c90f..7e627e73d 100644 --- a/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveStakingStep/StakeFormModal/index.tsx @@ -1,7 +1,7 @@ import React from "react" import TokenAmountForm from "#/components/shared/TokenAmountForm" import { TokenAmountFormValues } from "#/components/shared/TokenAmountForm/TokenAmountFormBase" -import { useMinStakeAmount, useWalletContext } from "#/hooks" +import { useMinDepositAmount, useWalletContext } from "#/hooks" import { FormSubmitButton } from "#/components/shared/Form" import StakeDetails from "./StakeDetails" @@ -10,7 +10,7 @@ function StakeFormModal({ }: { onSubmitForm: (values: TokenAmountFormValues) => void }) { - const minStakeAmount = useMinStakeAmount() + const minDepositAmount = useMinDepositAmount() const { btcAccount } = useWalletContext() const tokenBalance = BigInt(btcAccount?.balance.toString() ?? "0") @@ -19,12 +19,12 @@ function StakeFormModal({ tokenBalanceInputPlaceholder="BTC" currency="bitcoin" tokenBalance={tokenBalance} - minTokenAmount={minStakeAmount} + minTokenAmount={minDepositAmount} onSubmitForm={onSubmitForm} > Stake diff --git a/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx b/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx index 97fe66468..981a43b62 100644 --- a/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx +++ b/dapp/src/components/TransactionModal/ActiveUnstakingStep/UnstakeFormModal/index.tsx @@ -5,7 +5,7 @@ import { TokenAmountFormValues } from "#/components/shared/TokenAmountForm/Token import { TextMd, TextSm } from "#/components/shared/Typography" import Spinner from "#/components/shared/Spinner" import { FormSubmitButton } from "#/components/shared/Form" -import { useMinStakeAmount } from "#/hooks" +import { useMinDepositAmount } from "#/hooks" import UnstakeDetails from "./UnstakeDetails" // TODO: Use a position amount @@ -16,14 +16,14 @@ function UnstakeFormModal({ }: { onSubmitForm: (values: TokenAmountFormValues) => void }) { - const minStakeAmount = useMinStakeAmount() + const minDepositAmount = useMinDepositAmount() return ( diff --git a/dapp/src/hooks/sdk/index.ts b/dapp/src/hooks/sdk/index.ts index ffac77cf2..582413565 100644 --- a/dapp/src/hooks/sdk/index.ts +++ b/dapp/src/hooks/sdk/index.ts @@ -1,4 +1,4 @@ export * from "./useInitializeAcreSdk" -export * from "./useFetchMinStakeAmount" +export * from "./useFetchMinDepositAmount" export * from "./useFetchSdkData" export * from "./useFetchBTCBalance" diff --git a/dapp/src/hooks/sdk/useFetchMinStakeAmount.ts b/dapp/src/hooks/sdk/useFetchMinDepositAmount.ts similarity index 55% rename from dapp/src/hooks/sdk/useFetchMinStakeAmount.ts rename to dapp/src/hooks/sdk/useFetchMinDepositAmount.ts index 6b06b5e03..835de9918 100644 --- a/dapp/src/hooks/sdk/useFetchMinStakeAmount.ts +++ b/dapp/src/hooks/sdk/useFetchMinDepositAmount.ts @@ -1,22 +1,22 @@ import { useEffect } from "react" -import { setMinStakeAmount } from "#/store/btc" +import { setMinDepositAmount } from "#/store/btc" import { logPromiseFailure } from "#/utils" import { useAcreContext } from "#/acre-react/hooks" import { useAppDispatch } from "../store/useAppDispatch" -export function useFetchMinStakeAmount() { +export function useFetchMinDepositAmount() { const { acre, isInitialized } = useAcreContext() const dispatch = useAppDispatch() useEffect(() => { if (!isInitialized || !acre) return - const fetchMinStakeAmount = async () => { - const minStakeAmount = await acre.staking.minStakeAmount() + const fetchMinDepositAmount = async () => { + const minDepositAmount = await acre.staking.minDepositAmount() - dispatch(setMinStakeAmount(minStakeAmount)) + dispatch(setMinDepositAmount(minDepositAmount)) } - logPromiseFailure(fetchMinStakeAmount()) + logPromiseFailure(fetchMinDepositAmount()) }, [acre, dispatch, isInitialized]) } diff --git a/dapp/src/hooks/sdk/useFetchSdkData.ts b/dapp/src/hooks/sdk/useFetchSdkData.ts index 375a50db4..1472190a6 100644 --- a/dapp/src/hooks/sdk/useFetchSdkData.ts +++ b/dapp/src/hooks/sdk/useFetchSdkData.ts @@ -1,7 +1,7 @@ import { useFetchBTCBalance } from "./useFetchBTCBalance" -import { useFetchMinStakeAmount } from "./useFetchMinStakeAmount" +import { useFetchMinDepositAmount } from "./useFetchMinDepositAmount" export function useFetchSdkData() { useFetchBTCBalance() - useFetchMinStakeAmount() + useFetchMinDepositAmount() } diff --git a/dapp/src/hooks/store/index.ts b/dapp/src/hooks/store/index.ts index f34e76947..bdad282f8 100644 --- a/dapp/src/hooks/store/index.ts +++ b/dapp/src/hooks/store/index.ts @@ -2,4 +2,4 @@ export * from "./useAppDispatch" export * from "./useAppSelector" export * from "./useEstimatedBTCBalance" export * from "./useSharesBalance" -export * from "./useMinStakeAmount" +export * from "./useMinDepositAmount" diff --git a/dapp/src/hooks/store/useMinDepositAmount.ts b/dapp/src/hooks/store/useMinDepositAmount.ts new file mode 100644 index 000000000..082a0a68a --- /dev/null +++ b/dapp/src/hooks/store/useMinDepositAmount.ts @@ -0,0 +1,6 @@ +import { selectMinDepositAmount } from "#/store/btc" +import { useAppSelector } from "./useAppSelector" + +export function useMinDepositAmount() { + return useAppSelector(selectMinDepositAmount) +} diff --git a/dapp/src/hooks/store/useMinStakeAmount.ts b/dapp/src/hooks/store/useMinStakeAmount.ts deleted file mode 100644 index 96cde88d6..000000000 --- a/dapp/src/hooks/store/useMinStakeAmount.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { selectMinStakeAmount } from "#/store/btc" -import { useAppSelector } from "./useAppSelector" - -export function useMinStakeAmount() { - return useAppSelector(selectMinStakeAmount) -} diff --git a/dapp/src/store/btc/btcSelector.ts b/dapp/src/store/btc/btcSelector.ts index 058fccca7..88a511361 100644 --- a/dapp/src/store/btc/btcSelector.ts +++ b/dapp/src/store/btc/btcSelector.ts @@ -9,5 +9,5 @@ export const selectSharesBalance = (state: RootState): bigint => export const selectBtcUsdPrice = (state: RootState): number => state.btc.usdPrice -export const selectMinStakeAmount = (state: RootState) => - state.btc.minStakeAmount +export const selectMinDepositAmount = (state: RootState) => + state.btc.minDepositAmount diff --git a/dapp/src/store/btc/btcSlice.ts b/dapp/src/store/btc/btcSlice.ts index 617995479..0f69fb13e 100644 --- a/dapp/src/store/btc/btcSlice.ts +++ b/dapp/src/store/btc/btcSlice.ts @@ -6,7 +6,7 @@ type BtcState = { sharesBalance: bigint isLoadingPriceUSD: boolean usdPrice: number - minStakeAmount: bigint + minDepositAmount: bigint } const initialState: BtcState = { @@ -14,7 +14,7 @@ const initialState: BtcState = { sharesBalance: 0n, isLoadingPriceUSD: false, usdPrice: 0, - minStakeAmount: 0n, + minDepositAmount: 0n, } // Store Bitcoin data such as balance, balance in usd and other related data to Bitcoin chain. @@ -28,8 +28,8 @@ export const btcSlice = createSlice({ setEstimatedBtcBalance(state, action: PayloadAction) { state.estimatedBtcBalance = action.payload }, - setMinStakeAmount(state, action: PayloadAction) { - state.minStakeAmount = action.payload + setMinDepositAmount(state, action: PayloadAction) { + state.minDepositAmount = action.payload }, }, extraReducers: (builder) => { @@ -49,5 +49,5 @@ export const btcSlice = createSlice({ }, }) -export const { setSharesBalance, setEstimatedBtcBalance, setMinStakeAmount } = +export const { setSharesBalance, setEstimatedBtcBalance, setMinDepositAmount } = btcSlice.actions diff --git a/sdk/src/lib/contracts/bitcoin-depositor.ts b/sdk/src/lib/contracts/bitcoin-depositor.ts index 4e4695f77..05d3dd887 100644 --- a/sdk/src/lib/contracts/bitcoin-depositor.ts +++ b/sdk/src/lib/contracts/bitcoin-depositor.ts @@ -37,7 +37,7 @@ export interface BitcoinDepositor extends DepositorProxy { decodeExtraData(extraData: string): DecodedExtraData /** - * @returns Minimum stake amount. + * @returns Minimum deposit amount. */ - minStake(): Promise + minDepositAmount(): Promise } diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index 1ca5ab898..17228c4ea 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -132,11 +132,11 @@ class EthereumBitcoinDepositor } /** - * @see {BitcoinDepositor#minStake} + * @see {BitcoinDepositor#minDepositAmount} * @dev The value in tBTC token precision (1e18 precision). */ - async minStake(): Promise { - return this.instance.minStake() + async minDepositAmount(): Promise { + return this.instance.minDepositAmount() } } diff --git a/sdk/src/modules/staking/index.ts b/sdk/src/modules/staking/index.ts index 42a6be2df..bf6a69a93 100644 --- a/sdk/src/modules/staking/index.ts +++ b/sdk/src/modules/staking/index.ts @@ -81,10 +81,10 @@ class StakingModule { } /** - * @returns Minimum stake amount in 1e8 satoshi precision. + * @returns Minimum deposit amount in 1e8 satoshi precision. */ - async minStakeAmount() { - const value = await this.#contracts.bitcoinDepositor.minStake() + async minDepositAmount() { + const value = await this.#contracts.bitcoinDepositor.minDepositAmount() return toSatoshi(value) } } diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index 06a220918..fed57e00a 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -18,12 +18,12 @@ describe("BitcoinDepositor", () => { const vaultAddress = EthereumAddress.from( ethers.Wallet.createRandom().address, ) - const minStakeAmount = BigInt(0.015 * 1e18) + const minDepositAmount = BigInt(0.015 * 1e18) const mockedContractInstance = { tbtcVault: jest.fn().mockImplementation(() => vaultAddress.identifierHex), initializeDeposit: jest.fn(), - minStake: jest.fn().mockImplementation(() => minStakeAmount), + minDepositAmount: jest.fn().mockImplementation(() => minDepositAmount), } let depositor: EthereumBitcoinDepositor let depositorAddress: EthereumAddress @@ -248,11 +248,11 @@ describe("BitcoinDepositor", () => { ) }) - describe("minStake", () => { - it("should return minimum stake amount", async () => { - const result = await depositor.minStake() + describe("minDepositAmount", () => { + it("should return minimum deposit amount", async () => { + const result = await depositor.minDepositAmount() - expect(result).toEqual(minStakeAmount) + expect(result).toEqual(minDepositAmount) }) }) }) diff --git a/sdk/test/modules/staking.test.ts b/sdk/test/modules/staking.test.ts index 7e043ea70..e8a91b214 100644 --- a/sdk/test/modules/staking.test.ts +++ b/sdk/test/modules/staking.test.ts @@ -397,8 +397,8 @@ describe("Staking", () => { }) }) - describe("minStakeAmount", () => { - describe("should return minimum stake amount", () => { + describe("minDepositAmount", () => { + describe("should return minimum deposit amount", () => { const spyOnToSatoshi = jest.spyOn(satoshiConverterUtils, "toSatoshi") const mockedResult = BigInt(0.015 * 1e18) // The returned result should be in satoshi precision @@ -406,10 +406,10 @@ describe("Staking", () => { let result: bigint beforeAll(async () => { - contracts.bitcoinDepositor.minStake = jest + contracts.bitcoinDepositor.minDepositAmount = jest .fn() .mockResolvedValue(mockedResult) - result = await staking.minStakeAmount() + result = await staking.minDepositAmount() }) it("should convert value to 1e8 satoshi precision", () => { diff --git a/sdk/test/utils/mock-acre-contracts.ts b/sdk/test/utils/mock-acre-contracts.ts index 82d627cd2..6cdc670c3 100644 --- a/sdk/test/utils/mock-acre-contracts.ts +++ b/sdk/test/utils/mock-acre-contracts.ts @@ -13,7 +13,7 @@ export class MockAcreContracts implements AcreContracts { decodeExtraData: jest.fn(), encodeExtraData: jest.fn(), revealDeposit: jest.fn(), - minStake: jest.fn(), + minDepositAmount: jest.fn(), } as BitcoinDepositor this.stBTC = { From b0a016703f88a0d22a1697bfb3f580619958357c Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Fri, 12 Apr 2024 11:35:09 +0200 Subject: [PATCH 075/110] Rename from `useFetchSdkData` to `useInitDataFromSdk` --- dapp/src/hooks/sdk/index.ts | 2 +- .../hooks/sdk/{useFetchSdkData.ts => useInitDataFromSdk.ts} | 2 +- dapp/src/hooks/useInitApp.ts | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) rename dapp/src/hooks/sdk/{useFetchSdkData.ts => useInitDataFromSdk.ts} (82%) diff --git a/dapp/src/hooks/sdk/index.ts b/dapp/src/hooks/sdk/index.ts index 582413565..8d103f71e 100644 --- a/dapp/src/hooks/sdk/index.ts +++ b/dapp/src/hooks/sdk/index.ts @@ -1,4 +1,4 @@ export * from "./useInitializeAcreSdk" export * from "./useFetchMinDepositAmount" -export * from "./useFetchSdkData" +export * from "./useInitDataFromSdk" export * from "./useFetchBTCBalance" diff --git a/dapp/src/hooks/sdk/useFetchSdkData.ts b/dapp/src/hooks/sdk/useInitDataFromSdk.ts similarity index 82% rename from dapp/src/hooks/sdk/useFetchSdkData.ts rename to dapp/src/hooks/sdk/useInitDataFromSdk.ts index 1472190a6..56ade2b6a 100644 --- a/dapp/src/hooks/sdk/useFetchSdkData.ts +++ b/dapp/src/hooks/sdk/useInitDataFromSdk.ts @@ -1,7 +1,7 @@ import { useFetchBTCBalance } from "./useFetchBTCBalance" import { useFetchMinDepositAmount } from "./useFetchMinDepositAmount" -export function useFetchSdkData() { +export function useInitDataFromSdk() { useFetchBTCBalance() useFetchMinDepositAmount() } diff --git a/dapp/src/hooks/useInitApp.ts b/dapp/src/hooks/useInitApp.ts index 7065f102b..250c784af 100644 --- a/dapp/src/hooks/useInitApp.ts +++ b/dapp/src/hooks/useInitApp.ts @@ -1,4 +1,4 @@ -import { useFetchSdkData, useInitializeAcreSdk } from "./sdk" +import { useInitDataFromSdk, useInitializeAcreSdk } from "./sdk" import { useSentry } from "./sentry" import { useFetchBTCPriceUSD } from "./useFetchBTCPriceUSD" @@ -7,6 +7,6 @@ export function useInitApp() { // useDetectThemeMode() useSentry() useInitializeAcreSdk() - useFetchSdkData() + useInitDataFromSdk() useFetchBTCPriceUSD() } From b58049458ce43a0f6be2de717ee31cde85491705 Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Mon, 15 Apr 2024 14:48:24 +0200 Subject: [PATCH 076/110] Update sdk/src/lib/ethereum/contract.ts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Rafał Czajkowski <57687279+r-czajkowski@users.noreply.github.com> --- sdk/src/lib/ethereum/contract.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk/src/lib/ethereum/contract.ts b/sdk/src/lib/ethereum/contract.ts index 14c16907f..8c6943c68 100644 --- a/sdk/src/lib/ethereum/contract.ts +++ b/sdk/src/lib/ethereum/contract.ts @@ -38,7 +38,8 @@ export interface EthersContractConfig { */ address?: string /** - * Signer - will return a Contract which will act on behalf of that signer. The signer will sign all contract transactions. + * Signer - will return a Contract which will act on behalf of that signer. + * The signer will sign all contract transactions. */ signer: EthereumSigner } From 7dcae5e1397b44a079ed78ffbebeebfec8b5870e Mon Sep 17 00:00:00 2001 From: Karolina Kosiorowska Date: Mon, 15 Apr 2024 17:09:13 +0200 Subject: [PATCH 077/110] Change `zIndex` for toast component Let's set the toast to be in front of the component drawer to avoid confusion. --- dapp/src/theme/utils/zIndices.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dapp/src/theme/utils/zIndices.ts b/dapp/src/theme/utils/zIndices.ts index 4f196f66f..4eda9c324 100644 --- a/dapp/src/theme/utils/zIndices.ts +++ b/dapp/src/theme/utils/zIndices.ts @@ -1,5 +1,5 @@ export const zIndices = { sidebar: 1450, drawer: 1470, - toast: 1410, + toast: 1480, } From 26a1c63641be5d614f3f7ab72339ca38a38c1690 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Tue, 16 Apr 2024 12:55:28 +0200 Subject: [PATCH 078/110] Replace `staking` term with `deposit` We transition from stake to deposit naming. Here we only update places related to the estimating fees feature. We are going to update the term in a separate PR. --- sdk/src/lib/contracts/bitcoin-depositor.ts | 16 +++---- sdk/src/lib/ethereum/bitcoin-depositor.ts | 6 +-- sdk/src/modules/staking/index.ts | 24 +++++----- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 12 ++--- sdk/test/modules/staking.test.ts | 47 ++++++++++---------- sdk/test/utils/mock-acre-contracts.ts | 2 +- 6 files changed, 51 insertions(+), 56 deletions(-) diff --git a/sdk/src/lib/contracts/bitcoin-depositor.ts b/sdk/src/lib/contracts/bitcoin-depositor.ts index e98f751d7..efd628f09 100644 --- a/sdk/src/lib/contracts/bitcoin-depositor.ts +++ b/sdk/src/lib/contracts/bitcoin-depositor.ts @@ -33,9 +33,9 @@ type TBTCMintingFees = { } /** - * Represents the Acre network staking fees. + * Represents the Acre network deposit fees. */ -type AcreStakingFees = { +type AcreDepositFees = { /** * The Acre network depositor fee taken from each Bitcoin deposit and * transferred to the treasury upon stake request finalization. @@ -43,9 +43,9 @@ type AcreStakingFees = { bitcoinDepositorFee: bigint } -export type StakingFees = { +export type DepositFees = { tbtc: TBTCMintingFees - acre: AcreStakingFees + acre: AcreDepositFees } /** @@ -77,12 +77,12 @@ export interface BitcoinDepositor extends DepositorProxy { decodeExtraData(extraData: string): DecodedExtraData /** - * Estimates the staking fees based on the provided amount. - * @param amountToStake Amount to stake in 1e8 satoshi precision. - * @returns Staking fees grouped by tBTC and Acre networks in 1e18 tBTC token + * Estimates the deposit fees based on the provided amount. + * @param amountToDeposit Amount to deposit in 1e8 satoshi precision. + * @returns Deposit fees grouped by tBTC and Acre networks in 1e18 tBTC token * precision. */ - estimateStakingFees(amountToStake: bigint): Promise + estimateDepositFees(amountToDeposit: bigint): Promise /** * @returns Minimum deposit amount. diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index cc8b3d54f..71f8915bb 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -16,7 +16,7 @@ import { DecodedExtraData, BitcoinDepositor, DepositReceipt, - StakingFees, + DepositFees, } from "../contracts" import { BitcoinRawTxVectors } from "../bitcoin" import { EthereumAddress } from "./address" @@ -162,9 +162,9 @@ class EthereumBitcoinDepositor } /** - * @see {BitcoinDepositor#estimateStakingFees} + * @see {BitcoinDepositor#estimateDepositFees} */ - async estimateStakingFees(amountToStake: bigint): Promise { + async estimateDepositFees(amountToStake: bigint): Promise { const { depositTreasuryFeeDivisor, depositTxMaxFee, diff --git a/sdk/src/modules/staking/index.ts b/sdk/src/modules/staking/index.ts index c178e8774..d58dc9121 100644 --- a/sdk/src/modules/staking/index.ts +++ b/sdk/src/modules/staking/index.ts @@ -1,17 +1,13 @@ import { ChainIdentifier, TBTC } from "@keep-network/tbtc-v2.ts" -import { - AcreContracts, - DepositorProxy, - StakingFees as StakingFeesByNetwork, -} from "../../lib/contracts" +import { AcreContracts, DepositorProxy, DepositFees } from "../../lib/contracts" import { ChainEIP712Signer } from "../../lib/eip712-signer" import { StakeInitialization } from "./stake-initialization" import { toSatoshi } from "../../lib/utils" /** - * Represents all total staking fees grouped by network. + * Represents all total deposit fees grouped by network. */ -export type TotalStakingFees = { +export type TotalDepositFees = { tbtc: bigint acre: bigint total: bigint @@ -94,17 +90,17 @@ class StakingModule { } /** - * Estimates the staking fees based on the provided amount. - * @param amountToStake Amount to stake in satoshi. - * @returns Staking fees grouped by tBTC and Acre networks in 1e8 satoshi - * precision and total staking fees value. + * Estimates the deposit fees based on the provided amount. + * @param amount Amount to deposit in satoshi. + * @returns Deposit fees grouped by tBTC and Acre networks in 1e8 satoshi + * precision and total deposit fees value. */ - async estimateStakingFees(amount: bigint): Promise { + async estimateDepositFees(amount: bigint): Promise { const { acre: acreFees, tbtc: tbtcFees } = - await this.#contracts.bitcoinDepositor.estimateStakingFees(amount) + await this.#contracts.bitcoinDepositor.estimateDepositFees(amount) const sumFeesByNetwork = < - T extends StakingFeesByNetwork["tbtc"] | StakingFeesByNetwork["acre"], + T extends DepositFees["tbtc"] | DepositFees["acre"], >( fees: T, ) => Object.values(fees).reduce((reducer, fee) => reducer + fee, 0n) diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index 55c4fdd4d..9161f858b 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -4,7 +4,7 @@ import { EthereumAddress, Hex, EthereumSigner, - StakingFees, + DepositFees, } from "../../../src" import { extraDataValidTestData } from "./data" @@ -268,7 +268,7 @@ describe("BitcoinDepositor", () => { ) }) - describe("estimateStakingFees", () => { + describe("estimateDepositFees", () => { const mockedBridgeContractInstance = { depositsParameters: jest .fn() @@ -323,10 +323,10 @@ describe("BitcoinDepositor", () => { }) describe("when network fees are not yet cached", () => { - let result: StakingFees + let result: DepositFees beforeAll(async () => { - result = await depositor.estimateStakingFees(amountToStake) + result = await depositor.estimateDepositFees(amountToStake) }) it("should get the bridge contract address", () => { @@ -375,7 +375,7 @@ describe("BitcoinDepositor", () => { }) describe("when network fees are already cached", () => { - let result2: StakingFees + let result2: DepositFees beforeAll(async () => { mockedContractInstance.bridge.mockClear() @@ -384,7 +384,7 @@ describe("BitcoinDepositor", () => { mockedBridgeContractInstance.depositsParameters.mockClear() mockedVaultContractInstance.optimisticMintingFeeDivisor.mockClear() - result2 = await depositor.estimateStakingFees(amountToStake) + result2 = await depositor.estimateDepositFees(amountToStake) }) it("should get the deposit parameters from cache", () => { diff --git a/sdk/test/modules/staking.test.ts b/sdk/test/modules/staking.test.ts index c960dd7e4..68172bd1c 100644 --- a/sdk/test/modules/staking.test.ts +++ b/sdk/test/modules/staking.test.ts @@ -8,14 +8,13 @@ import { DepositorProxy, DepositReceipt, EthereumAddress, - StakingFees, - TotalStakingFees, + DepositFees, + TotalDepositFees, } from "../../src" import * as satoshiConverter from "../../src/lib/utils/satoshi-converter" import { MockAcreContracts } from "../utils/mock-acre-contracts" import { MockMessageSigner } from "../utils/mock-message-signer" import { MockTBTC } from "../utils/mock-tbtc" -import * as satoshiConverterUtils from "../../src/lib/utils/satoshi-converter" const stakingModuleData: { initializeStake: { @@ -25,10 +24,10 @@ const stakingModuleData: { bitcoinRecoveryAddress: string mockedDepositBTCAddress: string } - estimateStakingFees: { + estimateDepositFees: { amount: bigint - mockedStakingFees: StakingFees - expectedStakingFeesInSatoshi: TotalStakingFees + mockedDepositFees: DepositFees + expectedDepositFeesInSatoshi: TotalDepositFees } } = { initializeStake: { @@ -41,9 +40,9 @@ const stakingModuleData: { mockedDepositBTCAddress: "tb1qma629cu92skg0t86lftyaf9uflzwhp7jk63h6mpmv3ezh6puvdhs6w2r05", }, - estimateStakingFees: { + estimateDepositFees: { amount: 10_000_000n, // 0.1 BTC - mockedStakingFees: { + mockedDepositFees: { tbtc: { // 0.00005 tBTC in 1e18 precision. treasuryFee: 50000000000000n, @@ -57,7 +56,7 @@ const stakingModuleData: { bitcoinDepositorFee: 100000000000000n, }, }, - expectedStakingFeesInSatoshi: { + expectedDepositFeesInSatoshi: { tbtc: 124990n, acre: 10000n, total: 134990n, @@ -427,36 +426,36 @@ describe("Staking", () => { }) }) - describe("estimateStakingFees", () => { + describe("estimateDepositFees", () => { const { - estimateStakingFees: { + estimateDepositFees: { amount, - mockedStakingFees, - expectedStakingFeesInSatoshi, + mockedDepositFees, + expectedDepositFeesInSatoshi, }, } = stakingModuleData - let result: TotalStakingFees + let result: TotalDepositFees const spyOnToSatoshi = jest.spyOn(satoshiConverter, "toSatoshi") beforeAll(async () => { - contracts.bitcoinDepositor.estimateStakingFees = jest + contracts.bitcoinDepositor.estimateDepositFees = jest .fn() - .mockResolvedValue(mockedStakingFees) + .mockResolvedValue(mockedDepositFees) - result = await staking.estimateStakingFees(amount) + result = await staking.estimateDepositFees(amount) }) - it("should get the staking fees from Acre Bitcoin Depositor contract handle", () => { + it("should get the deposit fees from Acre Bitcoin Depositor contract handle", () => { expect( - contracts.bitcoinDepositor.estimateStakingFees, + contracts.bitcoinDepositor.estimateDepositFees, ).toHaveBeenCalledWith(amount) }) it("should convert tBTC network fees to satoshi", () => { const { tbtc: { depositTxMaxFee, treasuryFee, optimisticMintingFee }, - } = mockedStakingFees + } = mockedDepositFees const totalTbtcFees = depositTxMaxFee + treasuryFee + optimisticMintingFee expect(spyOnToSatoshi).toHaveBeenNthCalledWith(1, totalTbtcFees) @@ -465,20 +464,20 @@ describe("Staking", () => { it("should convert Acre network fees to satoshi", () => { const { acre: { bitcoinDepositorFee }, - } = mockedStakingFees + } = mockedDepositFees const totalAcreFees = bitcoinDepositorFee expect(spyOnToSatoshi).toHaveBeenNthCalledWith(2, totalAcreFees) }) - it("should return the staking fees in satoshi precision", () => { - expect(result).toMatchObject(expectedStakingFeesInSatoshi) + it("should return the deposit fees in satoshi precision", () => { + expect(result).toMatchObject(expectedDepositFeesInSatoshi) }) }) describe("minDepositAmount", () => { describe("should return minimum deposit amount", () => { - const spyOnToSatoshi = jest.spyOn(satoshiConverterUtils, "toSatoshi") + const spyOnToSatoshi = jest.spyOn(satoshiConverter, "toSatoshi") const mockedResult = BigInt(0.015 * 1e18) // The returned result should be in satoshi precision const expectedResult = BigInt(0.015 * 1e8) diff --git a/sdk/test/utils/mock-acre-contracts.ts b/sdk/test/utils/mock-acre-contracts.ts index 6d2ea8c1e..fe796e8f9 100644 --- a/sdk/test/utils/mock-acre-contracts.ts +++ b/sdk/test/utils/mock-acre-contracts.ts @@ -13,7 +13,7 @@ export class MockAcreContracts implements AcreContracts { decodeExtraData: jest.fn(), encodeExtraData: jest.fn(), revealDeposit: jest.fn(), - estimateStakingFees: jest.fn(), + estimateDepositFees: jest.fn(), minDepositAmount: jest.fn(), } as BitcoinDepositor From 4a454b8488faade8aa3b3269297831f1f71fce7b Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Tue, 16 Apr 2024 14:16:59 +0200 Subject: [PATCH 079/110] Update deposit fees calculation Take into account stBTC deposit fee taken from each tBTC deposit to the stBTC pool which is then transferred to the treasury. --- sdk/src/lib/contracts/stbtc.ts | 8 ++++++++ sdk/src/lib/ethereum/stbtc.ts | 14 ++++++++++++++ sdk/src/modules/staking/index.ts | 8 ++++++-- sdk/test/lib/ethereum/stbtc.test.ts | 27 +++++++++++++++++++++++++++ sdk/test/modules/staking.test.ts | 22 +++++++++++++++++++--- sdk/test/utils/mock-acre-contracts.ts | 1 + 6 files changed, 75 insertions(+), 5 deletions(-) diff --git a/sdk/src/lib/contracts/stbtc.ts b/sdk/src/lib/contracts/stbtc.ts index 5eac12c4f..53c048403 100644 --- a/sdk/src/lib/contracts/stbtc.ts +++ b/sdk/src/lib/contracts/stbtc.ts @@ -12,4 +12,12 @@ export interface StBTC { * @returns Maximum withdraw value. */ assetsBalanceOf(identifier: ChainIdentifier): Promise + + /** + * Calculates the deposit fee taken from each tBTC deposit to the stBTC pool + * which is then transferred to the treasury. + * @param amount Amount to deposit in 1e18 precision. + * @returns Deposit fee. + */ + depositFee(amount: bigint): Promise } diff --git a/sdk/src/lib/ethereum/stbtc.ts b/sdk/src/lib/ethereum/stbtc.ts index d4d44610c..6adb9ec9d 100644 --- a/sdk/src/lib/ethereum/stbtc.ts +++ b/sdk/src/lib/ethereum/stbtc.ts @@ -16,6 +16,8 @@ class EthereumStBTC extends EthersContractWrapper implements StBTC { + readonly #BASIS_POINT_SCALE = BigInt(1e4) + constructor(config: EthersContractConfig, network: EthereumNetwork) { let artifact: EthersContractDeployment @@ -44,6 +46,18 @@ class EthereumStBTC assetsBalanceOf(identifier: ChainIdentifier): Promise { return this.instance.assetsBalanceOf(`0x${identifier.identifierHex}`) } + + /** + * @see {StBTC#depositFee} + */ + async depositFee(amount: bigint): Promise { + const entryFeeBasisPoints = await this.instance.entryFeeBasisPoints() + + return ( + (amount * entryFeeBasisPoints) / + (entryFeeBasisPoints + this.#BASIS_POINT_SCALE) + ) + } } // eslint-disable-next-line import/prefer-default-export diff --git a/sdk/src/modules/staking/index.ts b/sdk/src/modules/staking/index.ts index d58dc9121..5cbce8050 100644 --- a/sdk/src/modules/staking/index.ts +++ b/sdk/src/modules/staking/index.ts @@ -2,7 +2,7 @@ import { ChainIdentifier, TBTC } from "@keep-network/tbtc-v2.ts" import { AcreContracts, DepositorProxy, DepositFees } from "../../lib/contracts" import { ChainEIP712Signer } from "../../lib/eip712-signer" import { StakeInitialization } from "./stake-initialization" -import { toSatoshi } from "../../lib/utils" +import { fromSatoshi, toSatoshi } from "../../lib/utils" /** * Represents all total deposit fees grouped by network. @@ -105,9 +105,13 @@ class StakingModule { fees: T, ) => Object.values(fees).reduce((reducer, fee) => reducer + fee, 0n) + const depositFee = await this.#contracts.stBTC.depositFee( + fromSatoshi(amount), + ) + const tbtc = toSatoshi(sumFeesByNetwork(tbtcFees)) - const acre = toSatoshi(sumFeesByNetwork(acreFees)) + const acre = toSatoshi(sumFeesByNetwork(acreFees)) + toSatoshi(depositFee) return { tbtc, diff --git a/sdk/test/lib/ethereum/stbtc.test.ts b/sdk/test/lib/ethereum/stbtc.test.ts index 4d6fa531d..898ef44b7 100644 --- a/sdk/test/lib/ethereum/stbtc.test.ts +++ b/sdk/test/lib/ethereum/stbtc.test.ts @@ -14,6 +14,7 @@ describe("stbtc", () => { const mockedContractInstance = { balanceOf: jest.fn(), assetsBalanceOf: jest.fn(), + entryFeeBasisPoints: jest.fn(), } beforeAll(() => { @@ -70,4 +71,30 @@ describe("stbtc", () => { expect(result).toEqual(expectedResult) }) }) + + describe("depositFee", () => { + // 0.1 in 1e18 precision + const amount = 100000000000000000n + const mockedEntryFeeBasisPointsValue = 1n + // (amount * basisPoints) / (basisPoints / 1e4) + const expectedResult = 9999000099990n + + let result: bigint + + beforeAll(async () => { + mockedContractInstance.entryFeeBasisPoints.mockResolvedValue( + mockedEntryFeeBasisPointsValue, + ) + + result = await stbtc.depositFee(amount) + }) + + it("should get the entry fee basis points from contract", () => { + expect(mockedContractInstance.entryFeeBasisPoints).toHaveBeenCalled() + }) + + it("should calculate the deposit fee correctly", () => { + expect(result).toEqual(expectedResult) + }) + }) }) diff --git a/sdk/test/modules/staking.test.ts b/sdk/test/modules/staking.test.ts index 68172bd1c..f34309bb1 100644 --- a/sdk/test/modules/staking.test.ts +++ b/sdk/test/modules/staking.test.ts @@ -26,7 +26,9 @@ const stakingModuleData: { } estimateDepositFees: { amount: bigint + amountIn1e18: bigint mockedDepositFees: DepositFees + stBTCDepositFee: bigint expectedDepositFeesInSatoshi: TotalDepositFees } } = { @@ -41,7 +43,9 @@ const stakingModuleData: { "tb1qma629cu92skg0t86lftyaf9uflzwhp7jk63h6mpmv3ezh6puvdhs6w2r05", }, estimateDepositFees: { - amount: 10_000_000n, // 0.1 BTC + amount: 10_000_000n, // 0.1 BTC, + // 0.1 tBTC in 1e18 precision. + amountIn1e18: 100000000000000000n, mockedDepositFees: { tbtc: { // 0.00005 tBTC in 1e18 precision. @@ -56,10 +60,12 @@ const stakingModuleData: { bitcoinDepositorFee: 100000000000000n, }, }, + // 0.001 in 1e18 precison + stBTCDepositFee: 1000000000000000n, expectedDepositFeesInSatoshi: { tbtc: 124990n, - acre: 10000n, - total: 134990n, + acre: 110000n, + total: 234990n, }, }, } @@ -430,22 +436,32 @@ describe("Staking", () => { const { estimateDepositFees: { amount, + amountIn1e18, mockedDepositFees, expectedDepositFeesInSatoshi, + stBTCDepositFee, }, } = stakingModuleData let result: TotalDepositFees const spyOnToSatoshi = jest.spyOn(satoshiConverter, "toSatoshi") + const spyOnFromSatoshi = jest.spyOn(satoshiConverter, "fromSatoshi") beforeAll(async () => { contracts.bitcoinDepositor.estimateDepositFees = jest .fn() .mockResolvedValue(mockedDepositFees) + contracts.stBTC.depositFee = jest.fn().mockResolvedValue(stBTCDepositFee) + result = await staking.estimateDepositFees(amount) }) + it("should get the stBTC deposit fee", () => { + expect(spyOnFromSatoshi).toHaveBeenNthCalledWith(1, amount) + expect(contracts.stBTC.depositFee).toHaveBeenCalledWith(amountIn1e18) + }) + it("should get the deposit fees from Acre Bitcoin Depositor contract handle", () => { expect( contracts.bitcoinDepositor.estimateDepositFees, diff --git a/sdk/test/utils/mock-acre-contracts.ts b/sdk/test/utils/mock-acre-contracts.ts index fe796e8f9..761d60f6b 100644 --- a/sdk/test/utils/mock-acre-contracts.ts +++ b/sdk/test/utils/mock-acre-contracts.ts @@ -20,6 +20,7 @@ export class MockAcreContracts implements AcreContracts { this.stBTC = { balanceOf: jest.fn(), assetsBalanceOf: jest.fn(), + depositFee: jest.fn(), } as StBTC } } From b26a8f9329d657d19e27449fbc45d733920c8989 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Tue, 16 Apr 2024 14:30:59 +0200 Subject: [PATCH 080/110] Update `estimateDepositFees` fn Use a consistent precision for both, input parameters and the values the function returns. --- sdk/src/lib/contracts/bitcoin-depositor.ts | 2 +- sdk/src/lib/ethereum/bitcoin-depositor.ts | 14 +++++--------- sdk/src/modules/staking/index.ts | 13 ++++++++----- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 2 +- sdk/test/modules/staking.test.ts | 9 ++++++--- 5 files changed, 21 insertions(+), 19 deletions(-) diff --git a/sdk/src/lib/contracts/bitcoin-depositor.ts b/sdk/src/lib/contracts/bitcoin-depositor.ts index efd628f09..e64573f62 100644 --- a/sdk/src/lib/contracts/bitcoin-depositor.ts +++ b/sdk/src/lib/contracts/bitcoin-depositor.ts @@ -78,7 +78,7 @@ export interface BitcoinDepositor extends DepositorProxy { /** * Estimates the deposit fees based on the provided amount. - * @param amountToDeposit Amount to deposit in 1e8 satoshi precision. + * @param amountToDeposit Amount to deposit in 1e18 token precision. * @returns Deposit fees grouped by tBTC and Acre networks in 1e18 tBTC token * precision. */ diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index 71f8915bb..c22a372c8 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -164,7 +164,7 @@ class EthereumBitcoinDepositor /** * @see {BitcoinDepositor#estimateDepositFees} */ - async estimateDepositFees(amountToStake: bigint): Promise { + async estimateDepositFees(amountToDeposit: bigint): Promise { const { depositTreasuryFeeDivisor, depositTxMaxFee, @@ -173,12 +173,10 @@ class EthereumBitcoinDepositor const treasuryFee = depositTreasuryFeeDivisor > 0 - ? amountToStake / depositTreasuryFeeDivisor + ? amountToDeposit / depositTreasuryFeeDivisor : 0n - // Both deposit amount and treasury fee are in the 1e8 satoshi precision. - // We need to convert them to the 1e18 TBTC precision. - const amountSubTreasury = fromSatoshi(amountToStake - treasuryFee) + const amountSubTreasury = amountToDeposit - treasuryFee const optimisticMintingFee = optimisticMintingFeeDivisor > 0 @@ -189,13 +187,11 @@ class EthereumBitcoinDepositor // Compute depositor fee. The fee is calculated based on the initial funding // transaction amount, before the tBTC protocol network fees were taken. const depositorFee = - depositorFeeDivisor > 0n - ? fromSatoshi(amountToStake) / depositorFeeDivisor - : 0n + depositorFeeDivisor > 0n ? amountToDeposit / depositorFeeDivisor : 0n return { tbtc: { - treasuryFee: fromSatoshi(treasuryFee), + treasuryFee, optimisticMintingFee, depositTxMaxFee: fromSatoshi(depositTxMaxFee), }, diff --git a/sdk/src/modules/staking/index.ts b/sdk/src/modules/staking/index.ts index 5cbce8050..563515838 100644 --- a/sdk/src/modules/staking/index.ts +++ b/sdk/src/modules/staking/index.ts @@ -96,8 +96,15 @@ class StakingModule { * precision and total deposit fees value. */ async estimateDepositFees(amount: bigint): Promise { + const amountInTokenPrecision = fromSatoshi(amount) + const { acre: acreFees, tbtc: tbtcFees } = - await this.#contracts.bitcoinDepositor.estimateDepositFees(amount) + await this.#contracts.bitcoinDepositor.estimateDepositFees( + amountInTokenPrecision, + ) + const depositFee = await this.#contracts.stBTC.depositFee( + amountInTokenPrecision, + ) const sumFeesByNetwork = < T extends DepositFees["tbtc"] | DepositFees["acre"], @@ -105,10 +112,6 @@ class StakingModule { fees: T, ) => Object.values(fees).reduce((reducer, fee) => reducer + fee, 0n) - const depositFee = await this.#contracts.stBTC.depositFee( - fromSatoshi(amount), - ) - const tbtc = toSatoshi(sumFeesByNetwork(tbtcFees)) const acre = toSatoshi(sumFeesByNetwork(acreFees)) + toSatoshi(depositFee) diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index 9161f858b..c3cf80f90 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -281,7 +281,7 @@ describe("BitcoinDepositor", () => { .mockResolvedValue(testData.optimisticMintingFeeDivisor), } - const amountToStake = 10_000_000n // 0.1 BTC + const amountToStake = 100000000000000000n // 0.1 in 1e18 token precision const expectedResult = { tbtc: { diff --git a/sdk/test/modules/staking.test.ts b/sdk/test/modules/staking.test.ts index f34309bb1..d7eace5b4 100644 --- a/sdk/test/modules/staking.test.ts +++ b/sdk/test/modules/staking.test.ts @@ -457,15 +457,18 @@ describe("Staking", () => { result = await staking.estimateDepositFees(amount) }) - it("should get the stBTC deposit fee", () => { + it("should convert provided amount from satoshi to token precision", () => { expect(spyOnFromSatoshi).toHaveBeenNthCalledWith(1, amount) - expect(contracts.stBTC.depositFee).toHaveBeenCalledWith(amountIn1e18) }) it("should get the deposit fees from Acre Bitcoin Depositor contract handle", () => { expect( contracts.bitcoinDepositor.estimateDepositFees, - ).toHaveBeenCalledWith(amount) + ).toHaveBeenCalledWith(amountIn1e18) + }) + + it("should get the stBTC deposit fee", () => { + expect(contracts.stBTC.depositFee).toHaveBeenCalledWith(amountIn1e18) }) it("should convert tBTC network fees to satoshi", () => { From 0128a152322d6284a591edd6b1d4d72a8160812c Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Tue, 16 Apr 2024 15:15:24 +0200 Subject: [PATCH 081/110] Fix typos in comments --- sdk/src/lib/contracts/bitcoin-depositor.ts | 12 +++++------- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 2 +- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/sdk/src/lib/contracts/bitcoin-depositor.ts b/sdk/src/lib/contracts/bitcoin-depositor.ts index e64573f62..0a3830df8 100644 --- a/sdk/src/lib/contracts/bitcoin-depositor.ts +++ b/sdk/src/lib/contracts/bitcoin-depositor.ts @@ -25,20 +25,19 @@ type TBTCMintingFees = { */ optimisticMintingFee: bigint /** - * Maximum amount of BTC transaction fee that can - * be incurred by each swept deposit being part of the given sweep - * transaction. + * Maximum amount of BTC transaction fee that can be incurred by each swept + * deposit being part of the given sweep transaction. */ depositTxMaxFee: bigint } /** - * Represents the Acre network deposit fees. + * Represents the Acre protocol deposit fees. */ type AcreDepositFees = { /** - * The Acre network depositor fee taken from each Bitcoin deposit and - * transferred to the treasury upon stake request finalization. + * The Acre protocol depositor fee taken from each Bitcoin deposit and + * transferred to the treasury upon deposit request finalization. */ bitcoinDepositorFee: bigint } @@ -49,7 +48,6 @@ export type DepositFees = { } /** - * Interface for communication with the AcreBitcoinDepositor on-chain contract. * Interface for communication with the BitcoinDepositor on-chain contract. */ export interface BitcoinDepositor extends DepositorProxy { diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index c3cf80f90..d23d8d51d 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -19,7 +19,7 @@ const testData = { depositTreasuryFeeDivisor: 2_000n, // 1/2000 == 5bps == 0.05% == 0.0005 depositTxMaxFee: 100_000n, // 100000 satoshi = 0.001 BTC }, - optimisticMintingFeeDivisor: 500n, // 1/500 = 0.002 = 0.2%0 + optimisticMintingFeeDivisor: 500n, // 1/500 = 0.002 = 0.2% } describe("BitcoinDepositor", () => { From cd2da4bb1aa6dffd75280b6877818939ebe946ee Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Tue, 16 Apr 2024 15:17:37 +0200 Subject: [PATCH 082/110] Simplify statement in `depositorFeeDivisor` fn --- sdk/src/lib/ethereum/bitcoin-depositor.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index c22a372c8..9f849e2c8 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -233,9 +233,7 @@ class EthereumBitcoinDepositor return this.#cache.depositorFeeDivisor } - const depositorFeeDivisor = await this.instance.depositorFeeDivisor() - - this.#cache.depositorFeeDivisor = depositorFeeDivisor + this.#cache.depositorFeeDivisor = await this.instance.depositorFeeDivisor() return this.#cache.depositorFeeDivisor } From 1614c5ab28aa018a0763b48d5c34041e4699ab77 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Tue, 16 Apr 2024 15:22:01 +0200 Subject: [PATCH 083/110] Make function names consistent Make `BitcoinDepositor#estimateDepositFees` and `StBTC#depositFee` function names consistent. It was a little confusing to have `estimate` prefix in one but not in the other. Rename to `calculateDepositFee` in both. --- sdk/src/lib/contracts/bitcoin-depositor.ts | 4 ++-- sdk/src/lib/contracts/stbtc.ts | 2 +- sdk/src/lib/ethereum/bitcoin-depositor.ts | 4 ++-- sdk/src/lib/ethereum/stbtc.ts | 4 ++-- sdk/src/modules/staking/index.ts | 4 ++-- sdk/test/lib/ethereum/stbtc.test.ts | 2 +- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 4 ++-- sdk/test/modules/staking.test.ts | 12 ++++++++---- sdk/test/utils/mock-acre-contracts.ts | 4 ++-- 9 files changed, 22 insertions(+), 18 deletions(-) diff --git a/sdk/src/lib/contracts/bitcoin-depositor.ts b/sdk/src/lib/contracts/bitcoin-depositor.ts index 0a3830df8..baa71a770 100644 --- a/sdk/src/lib/contracts/bitcoin-depositor.ts +++ b/sdk/src/lib/contracts/bitcoin-depositor.ts @@ -75,12 +75,12 @@ export interface BitcoinDepositor extends DepositorProxy { decodeExtraData(extraData: string): DecodedExtraData /** - * Estimates the deposit fees based on the provided amount. + * Calculates the deposit fee based on the provided amount. * @param amountToDeposit Amount to deposit in 1e18 token precision. * @returns Deposit fees grouped by tBTC and Acre networks in 1e18 tBTC token * precision. */ - estimateDepositFees(amountToDeposit: bigint): Promise + calculateDepositFee(amountToDeposit: bigint): Promise /** * @returns Minimum deposit amount. diff --git a/sdk/src/lib/contracts/stbtc.ts b/sdk/src/lib/contracts/stbtc.ts index 53c048403..b94b71a34 100644 --- a/sdk/src/lib/contracts/stbtc.ts +++ b/sdk/src/lib/contracts/stbtc.ts @@ -19,5 +19,5 @@ export interface StBTC { * @param amount Amount to deposit in 1e18 precision. * @returns Deposit fee. */ - depositFee(amount: bigint): Promise + calculateDepositFee(amount: bigint): Promise } diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index 9f849e2c8..52f634c24 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -162,9 +162,9 @@ class EthereumBitcoinDepositor } /** - * @see {BitcoinDepositor#estimateDepositFees} + * @see {BitcoinDepositor#calculateDepositFee} */ - async estimateDepositFees(amountToDeposit: bigint): Promise { + async calculateDepositFee(amountToDeposit: bigint): Promise { const { depositTreasuryFeeDivisor, depositTxMaxFee, diff --git a/sdk/src/lib/ethereum/stbtc.ts b/sdk/src/lib/ethereum/stbtc.ts index 6adb9ec9d..94e3d0114 100644 --- a/sdk/src/lib/ethereum/stbtc.ts +++ b/sdk/src/lib/ethereum/stbtc.ts @@ -48,9 +48,9 @@ class EthereumStBTC } /** - * @see {StBTC#depositFee} + * @see {StBTC#calculateDepositFee} */ - async depositFee(amount: bigint): Promise { + async calculateDepositFee(amount: bigint): Promise { const entryFeeBasisPoints = await this.instance.entryFeeBasisPoints() return ( diff --git a/sdk/src/modules/staking/index.ts b/sdk/src/modules/staking/index.ts index 563515838..f1f7d5a4f 100644 --- a/sdk/src/modules/staking/index.ts +++ b/sdk/src/modules/staking/index.ts @@ -99,10 +99,10 @@ class StakingModule { const amountInTokenPrecision = fromSatoshi(amount) const { acre: acreFees, tbtc: tbtcFees } = - await this.#contracts.bitcoinDepositor.estimateDepositFees( + await this.#contracts.bitcoinDepositor.calculateDepositFee( amountInTokenPrecision, ) - const depositFee = await this.#contracts.stBTC.depositFee( + const depositFee = await this.#contracts.stBTC.calculateDepositFee( amountInTokenPrecision, ) diff --git a/sdk/test/lib/ethereum/stbtc.test.ts b/sdk/test/lib/ethereum/stbtc.test.ts index 898ef44b7..85b90c677 100644 --- a/sdk/test/lib/ethereum/stbtc.test.ts +++ b/sdk/test/lib/ethereum/stbtc.test.ts @@ -86,7 +86,7 @@ describe("stbtc", () => { mockedEntryFeeBasisPointsValue, ) - result = await stbtc.depositFee(amount) + result = await stbtc.calculateDepositFee(amount) }) it("should get the entry fee basis points from contract", () => { diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index d23d8d51d..882ea534a 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -326,7 +326,7 @@ describe("BitcoinDepositor", () => { let result: DepositFees beforeAll(async () => { - result = await depositor.estimateDepositFees(amountToStake) + result = await depositor.calculateDepositFee(amountToStake) }) it("should get the bridge contract address", () => { @@ -384,7 +384,7 @@ describe("BitcoinDepositor", () => { mockedBridgeContractInstance.depositsParameters.mockClear() mockedVaultContractInstance.optimisticMintingFeeDivisor.mockClear() - result2 = await depositor.estimateDepositFees(amountToStake) + result2 = await depositor.calculateDepositFee(amountToStake) }) it("should get the deposit parameters from cache", () => { diff --git a/sdk/test/modules/staking.test.ts b/sdk/test/modules/staking.test.ts index d7eace5b4..0d7aefd38 100644 --- a/sdk/test/modules/staking.test.ts +++ b/sdk/test/modules/staking.test.ts @@ -448,11 +448,13 @@ describe("Staking", () => { const spyOnFromSatoshi = jest.spyOn(satoshiConverter, "fromSatoshi") beforeAll(async () => { - contracts.bitcoinDepositor.estimateDepositFees = jest + contracts.bitcoinDepositor.calculateDepositFee = jest .fn() .mockResolvedValue(mockedDepositFees) - contracts.stBTC.depositFee = jest.fn().mockResolvedValue(stBTCDepositFee) + contracts.stBTC.calculateDepositFee = jest + .fn() + .mockResolvedValue(stBTCDepositFee) result = await staking.estimateDepositFees(amount) }) @@ -463,12 +465,14 @@ describe("Staking", () => { it("should get the deposit fees from Acre Bitcoin Depositor contract handle", () => { expect( - contracts.bitcoinDepositor.estimateDepositFees, + contracts.bitcoinDepositor.calculateDepositFee, ).toHaveBeenCalledWith(amountIn1e18) }) it("should get the stBTC deposit fee", () => { - expect(contracts.stBTC.depositFee).toHaveBeenCalledWith(amountIn1e18) + expect(contracts.stBTC.calculateDepositFee).toHaveBeenCalledWith( + amountIn1e18, + ) }) it("should convert tBTC network fees to satoshi", () => { diff --git a/sdk/test/utils/mock-acre-contracts.ts b/sdk/test/utils/mock-acre-contracts.ts index 761d60f6b..9a111cffc 100644 --- a/sdk/test/utils/mock-acre-contracts.ts +++ b/sdk/test/utils/mock-acre-contracts.ts @@ -13,14 +13,14 @@ export class MockAcreContracts implements AcreContracts { decodeExtraData: jest.fn(), encodeExtraData: jest.fn(), revealDeposit: jest.fn(), - estimateDepositFees: jest.fn(), + calculateDepositFee: jest.fn(), minDepositAmount: jest.fn(), } as BitcoinDepositor this.stBTC = { balanceOf: jest.fn(), assetsBalanceOf: jest.fn(), - depositFee: jest.fn(), + calculateDepositFee: jest.fn(), } as StBTC } } From 211bba757a00894b632917ed6d708812d7e284d4 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Tue, 16 Apr 2024 15:30:45 +0200 Subject: [PATCH 084/110] Cache the `entryFeeBasisPoints` value This value doesn't change often that's why we want to cache it per `StBTC` contract handle instance. --- sdk/src/lib/ethereum/stbtc.ts | 16 +++++++++- sdk/test/lib/ethereum/stbtc.test.ts | 46 ++++++++++++++++++++++------- 2 files changed, 50 insertions(+), 12 deletions(-) diff --git a/sdk/src/lib/ethereum/stbtc.ts b/sdk/src/lib/ethereum/stbtc.ts index 94e3d0114..e1304529e 100644 --- a/sdk/src/lib/ethereum/stbtc.ts +++ b/sdk/src/lib/ethereum/stbtc.ts @@ -18,6 +18,10 @@ class EthereumStBTC { readonly #BASIS_POINT_SCALE = BigInt(1e4) + #cache: { + entryFeeBasisPoints?: bigint + } = { entryFeeBasisPoints: undefined } + constructor(config: EthersContractConfig, network: EthereumNetwork) { let artifact: EthersContractDeployment @@ -51,13 +55,23 @@ class EthereumStBTC * @see {StBTC#calculateDepositFee} */ async calculateDepositFee(amount: bigint): Promise { - const entryFeeBasisPoints = await this.instance.entryFeeBasisPoints() + const entryFeeBasisPoints = await this.#getEntryFeeBasisPoints() return ( (amount * entryFeeBasisPoints) / (entryFeeBasisPoints + this.#BASIS_POINT_SCALE) ) } + + async #getEntryFeeBasisPoints(): Promise { + if (this.#cache.entryFeeBasisPoints) { + return this.#cache.entryFeeBasisPoints + } + + this.#cache.entryFeeBasisPoints = await this.instance.entryFeeBasisPoints() + + return this.#cache.entryFeeBasisPoints + } } // eslint-disable-next-line import/prefer-default-export diff --git a/sdk/test/lib/ethereum/stbtc.test.ts b/sdk/test/lib/ethereum/stbtc.test.ts index 85b90c677..08c7dddc0 100644 --- a/sdk/test/lib/ethereum/stbtc.test.ts +++ b/sdk/test/lib/ethereum/stbtc.test.ts @@ -81,20 +81,44 @@ describe("stbtc", () => { let result: bigint - beforeAll(async () => { - mockedContractInstance.entryFeeBasisPoints.mockResolvedValue( - mockedEntryFeeBasisPointsValue, - ) - - result = await stbtc.calculateDepositFee(amount) + describe("when the entry fee basis points value is not yet cached", () => { + beforeAll(async () => { + mockedContractInstance.entryFeeBasisPoints.mockResolvedValue( + mockedEntryFeeBasisPointsValue, + ) + + result = await stbtc.calculateDepositFee(amount) + }) + + it("should get the entry fee basis points from contract", () => { + expect(mockedContractInstance.entryFeeBasisPoints).toHaveBeenCalled() + }) + + it("should calculate the deposit fee correctly", () => { + expect(result).toEqual(expectedResult) + }) }) - it("should get the entry fee basis points from contract", () => { - expect(mockedContractInstance.entryFeeBasisPoints).toHaveBeenCalled() - }) + describe("the entry fee basis points value is cached", () => { + beforeAll(async () => { + mockedContractInstance.entryFeeBasisPoints.mockResolvedValue( + mockedEntryFeeBasisPointsValue, + ) - it("should calculate the deposit fee correctly", () => { - expect(result).toEqual(expectedResult) + await stbtc.calculateDepositFee(amount) + + result = await stbtc.calculateDepositFee(amount) + }) + + it("should get the entry fee basis points from cache", () => { + expect( + mockedContractInstance.entryFeeBasisPoints, + ).toHaveBeenCalledTimes(1) + }) + + it("should calculate the deposit fee correctly", () => { + expect(result).toEqual(expectedResult) + }) }) }) }) From 1a21936b7d5dfd79ee67636280d5a93e6706ed9f Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Tue, 16 Apr 2024 15:34:07 +0200 Subject: [PATCH 085/110] Rename variables/types/functions in staking module --- sdk/src/modules/staking/index.ts | 16 ++++++++-------- sdk/test/modules/staking.test.ts | 8 ++++---- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/sdk/src/modules/staking/index.ts b/sdk/src/modules/staking/index.ts index f1f7d5a4f..32e8b5363 100644 --- a/sdk/src/modules/staking/index.ts +++ b/sdk/src/modules/staking/index.ts @@ -7,7 +7,7 @@ import { fromSatoshi, toSatoshi } from "../../lib/utils" /** * Represents all total deposit fees grouped by network. */ -export type TotalDepositFees = { +export type DepositFee = { tbtc: bigint acre: bigint total: bigint @@ -90,12 +90,12 @@ class StakingModule { } /** - * Estimates the deposit fees based on the provided amount. + * Estimates the deposit fee based on the provided amount. * @param amount Amount to deposit in satoshi. - * @returns Deposit fees grouped by tBTC and Acre networks in 1e8 satoshi - * precision and total deposit fees value. + * @returns Deposit fee grouped by tBTC and Acre networks in 1e8 satoshi + * precision and total deposit fee value. */ - async estimateDepositFees(amount: bigint): Promise { + async estimateDepositFee(amount: bigint): Promise { const amountInTokenPrecision = fromSatoshi(amount) const { acre: acreFees, tbtc: tbtcFees } = @@ -106,15 +106,15 @@ class StakingModule { amountInTokenPrecision, ) - const sumFeesByNetwork = < + const sumFeesByProtocol = < T extends DepositFees["tbtc"] | DepositFees["acre"], >( fees: T, ) => Object.values(fees).reduce((reducer, fee) => reducer + fee, 0n) - const tbtc = toSatoshi(sumFeesByNetwork(tbtcFees)) + const tbtc = toSatoshi(sumFeesByProtocol(tbtcFees)) - const acre = toSatoshi(sumFeesByNetwork(acreFees)) + toSatoshi(depositFee) + const acre = toSatoshi(sumFeesByProtocol(acreFees)) + toSatoshi(depositFee) return { tbtc, diff --git a/sdk/test/modules/staking.test.ts b/sdk/test/modules/staking.test.ts index 0d7aefd38..81909295e 100644 --- a/sdk/test/modules/staking.test.ts +++ b/sdk/test/modules/staking.test.ts @@ -9,7 +9,7 @@ import { DepositReceipt, EthereumAddress, DepositFees, - TotalDepositFees, + DepositFee, } from "../../src" import * as satoshiConverter from "../../src/lib/utils/satoshi-converter" import { MockAcreContracts } from "../utils/mock-acre-contracts" @@ -29,7 +29,7 @@ const stakingModuleData: { amountIn1e18: bigint mockedDepositFees: DepositFees stBTCDepositFee: bigint - expectedDepositFeesInSatoshi: TotalDepositFees + expectedDepositFeesInSatoshi: DepositFee } } = { initializeStake: { @@ -443,7 +443,7 @@ describe("Staking", () => { }, } = stakingModuleData - let result: TotalDepositFees + let result: DepositFee const spyOnToSatoshi = jest.spyOn(satoshiConverter, "toSatoshi") const spyOnFromSatoshi = jest.spyOn(satoshiConverter, "fromSatoshi") @@ -456,7 +456,7 @@ describe("Staking", () => { .fn() .mockResolvedValue(stBTCDepositFee) - result = await staking.estimateDepositFees(amount) + result = await staking.estimateDepositFee(amount) }) it("should convert provided amount from satoshi to token precision", () => { From 97014f7e0a441abeb3f554007ef688ca6b8e6692 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Sat, 20 Apr 2024 09:01:20 +0200 Subject: [PATCH 086/110] Accessing 'exitFeeBasisPoints' var directly --- solidity/contracts/stBTC.sol | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/solidity/contracts/stBTC.sol b/solidity/contracts/stBTC.sol index e45d81cb0..458364380 100644 --- a/solidity/contracts/stBTC.sol +++ b/solidity/contracts/stBTC.sol @@ -255,8 +255,7 @@ contract stBTC is ERC4626Fees, PausableOwnable { uint256 currentAssetsBalance = IERC20(asset()).balanceOf(address(this)); // If there is not enough assets in stBTC to cover user withdrawals and // withdrawal fees then pull the assets from the dispatcher. - uint256 assetsWithFees = assets + - _feeOnRaw(assets, _exitFeeBasisPoints()); + uint256 assetsWithFees = assets + _feeOnRaw(assets, exitFeeBasisPoints); if (assetsWithFees > currentAssetsBalance) { dispatcher.withdraw(assetsWithFees - currentAssetsBalance); } From 0e94c587a695813bff7e61edf44cdb36f91b14b7 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Sat, 20 Apr 2024 09:47:17 +0200 Subject: [PATCH 087/110] Adding tests when the entry and exit fees are 0 --- solidity/test/stBTC.test.ts | 124 ++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) diff --git a/solidity/test/stBTC.test.ts b/solidity/test/stBTC.test.ts index 6bedff977..13881daee 100644 --- a/solidity/test/stBTC.test.ts +++ b/solidity/test/stBTC.test.ts @@ -963,6 +963,68 @@ describe("stBTC", () => { ) }) }) + + context("when the entry and exit fee is zero", () => { + beforeAfterSnapshotWrapper() + + context("when redeeming from a single deposit", () => { + beforeAfterSnapshotWrapper() + + const amountToDeposit = to1e18(1) + let tx: ContractTransactionResponse + + before(async () => { + await stbtc.connect(governance).updateExitFeeBasisPoints(0) + await stbtc.connect(governance).updateEntryFeeBasisPoints(0) + + await tbtc + .connect(depositor1) + .approve(await stbtc.getAddress(), amountToDeposit) + + await stbtc + .connect(depositor1) + .deposit(amountToDeposit, depositor1.address) + tx = await stbtc + .connect(depositor1) + .redeem(amountToDeposit, thirdParty, depositor1) + }) + + it("should emit Withdraw event", async () => { + await expect(tx).to.emit(stbtc, "Withdraw").withArgs( + // Caller. + depositor1.address, + // Receiver + thirdParty.address, + // Owner + depositor1.address, + // Redeemed tokens. + amountToDeposit, + // Burned shares. + amountToDeposit, + ) + }) + + it("should burn stBTC tokens", async () => { + await expect(tx).to.changeTokenBalances( + stbtc, + [depositor1.address], + [-amountToDeposit], + ) + }) + + it("should transfer tBTC tokens to a receiver", async () => { + await expect(tx).to.changeTokenBalances( + tbtc, + [thirdParty.address], + [amountToDeposit], + ) + }) + + it("should not transfer any tBTC tokens to Treasury", async () => { + await expect(tx).to.changeTokenBalances(tbtc, [treasury.address], [0]) + }) + }) + }) }) describe("withdraw", () => { @@ -1179,6 +1241,68 @@ describe("stBTC", () => { ) }) }) + + context("when the entry and exit fee is zero", () => { + beforeAfterSnapshotWrapper() + + context("when withdrawing from a single deposit", () => { + beforeAfterSnapshotWrapper() + + const amountToDeposit = to1e18(1) + let tx: ContractTransactionResponse + + before(async () => { + await stbtc.connect(governance).updateExitFeeBasisPoints(0) + await stbtc.connect(governance).updateEntryFeeBasisPoints(0) + + await tbtc + .connect(depositor1) + .approve(await stbtc.getAddress(), amountToDeposit) + + await stbtc + .connect(depositor1) + .deposit(amountToDeposit, depositor1.address) + tx = await stbtc + .connect(depositor1) + .withdraw(amountToDeposit, thirdParty, depositor1) + }) + + it("should emit Withdraw event", async () => { + await expect(tx).to.emit(stbtc, "Withdraw").withArgs( + // Caller. + depositor1.address, + // Receiver + thirdParty.address, + // Owner + depositor1.address, + // Withdrew tokens. + amountToDeposit, + // Burned shares. + amountToDeposit, + ) + }) + + it("should burn stBTC tokens", async () => { + await expect(tx).to.changeTokenBalances( + stbtc, + [depositor1.address], + [-amountToDeposit], + ) + }) + + it("should transfer tBTC tokens to a receiver", async () => { + await expect(tx).to.changeTokenBalances( + tbtc, + [thirdParty.address], + [amountToDeposit], + ) + }) + + it("should not transfer any tBTC tokens to Treasury", async () => { + await expect(tx).to.changeTokenBalances(tbtc, [treasury.address], [0]) + }) + }) + }) }) describe("updateMinimumDepositAmount", () => { From d403a3c01a05de29d9f6318ebaebd0cd553fb71f Mon Sep 17 00:00:00 2001 From: Dmitry Date: Sat, 20 Apr 2024 10:23:29 +0200 Subject: [PATCH 088/110] Covering cases when all the assets were allocated to Mezo Portal --- solidity/test/stBTC.test.ts | 146 ++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) diff --git a/solidity/test/stBTC.test.ts b/solidity/test/stBTC.test.ts index 13881daee..b9a990c82 100644 --- a/solidity/test/stBTC.test.ts +++ b/solidity/test/stBTC.test.ts @@ -878,6 +878,77 @@ describe("stBTC", () => { }) }) + context("when stBTC allocated all of the assets", () => { + beforeAfterSnapshotWrapper() + + let tx: ContractTransactionResponse + let firstDepositBalance: bigint + + const amountToDeposit = to1e18(3) + + before(async () => { + await tbtc.mint(depositor1.address, amountToDeposit) + await tbtc + .connect(depositor1) + .approve(await stbtc.getAddress(), amountToDeposit) + // Depositor deposits 3 tBTC. + await stbtc + .connect(depositor1) + .deposit(amountToDeposit, depositor1.address) + // Allocate 3 tBTC to Mezo Portal. + await mezoAllocator.connect(maintainer).allocate() + firstDepositBalance = await mezoAllocator.depositBalance() + // Depositor redeems 2 stBTC. + tx = await stbtc + .connect(depositor1) + .redeem(to1e18(2), depositor1, depositor1) + }) + + it("should transfer tBTC back to a depositor1", async () => { + const expectedRedeemedAssets = await stbtc.previewRedeem(to1e18(2)) + await expect(tx).to.changeTokenBalances( + tbtc, + [depositor1.address], + [expectedRedeemedAssets], + ) + }) + + it("should transfer redeem fee to Treasury", async () => { + const assetsToWithdraw = await stbtc.previewRedeem(to1e18(2)) + const redeemFee = feeOnRaw(assetsToWithdraw, exitFeeBasisPoints) + await expect(tx).to.changeTokenBalances( + tbtc, + [treasury.address], + [redeemFee], + ) + }) + + it("should decrease the deposit balance tracking in Mezo Allocator", async () => { + const depositBalance = await mezoAllocator.depositBalance() + const assetsToWithdraw = await stbtc.previewRedeem(to1e18(2)) + const redeemFee = feeOnRaw(assetsToWithdraw, exitFeeBasisPoints) + const assetsToWithdrawFromMezo = assetsToWithdraw + redeemFee + + expect(depositBalance).to.be.eq( + firstDepositBalance - assetsToWithdrawFromMezo, + ) + }) + + it("should emit Withdraw event", async () => { + const assetsToWithdraw = await stbtc.previewRedeem(to1e18(2)) + + await expect(tx) + .to.emit(stbtc, "Withdraw") + .withArgs( + depositor1.address, + depositor1.address, + depositor1.address, + assetsToWithdraw, + to1e18(2), + ) + }) + }) + context("when stBTC allocated some of the assets", () => { beforeAfterSnapshotWrapper() @@ -1164,6 +1235,81 @@ describe("stBTC", () => { }) }) + context("when stBTC allocated all of the assets", () => { + beforeAfterSnapshotWrapper() + + let tx: ContractTransactionResponse + let firstDepositBalance: bigint + + const amountToDeposit = to1e18(3) + + before(async () => { + await tbtc.mint(depositor1.address, amountToDeposit) + await tbtc + .connect(depositor1) + .approve(await stbtc.getAddress(), amountToDeposit) + // Depositor deposits 3 tBTC. + await stbtc + .connect(depositor1) + .deposit(amountToDeposit, depositor1.address) + // Allocate 3 tBTC to Mezo Portal. + await mezoAllocator.connect(maintainer).allocate() + firstDepositBalance = await mezoAllocator.depositBalance() + // Depositor withdraws 2 stBTC. + tx = await stbtc + .connect(depositor1) + .withdraw(to1e18(2), depositor1, depositor1) + }) + + it("should transfer tBTC back to a depositor1", async () => { + const expectedWithdrawnAssets = to1e18(2) + + await expect(tx).to.changeTokenBalances( + tbtc, + [depositor1.address], + [expectedWithdrawnAssets], + ) + }) + + it("should transfer withdrawal fee to Treasury", async () => { + const assetsToWithdraw = to1e18(2) + const withdrawFee = feeOnRaw(assetsToWithdraw, exitFeeBasisPoints) + + await expect(tx).to.changeTokenBalances( + tbtc, + [treasury.address], + [withdrawFee], + ) + }) + + it("should decrease the deposit balance tracking in Mezo Allocator", async () => { + const depositBalance = await mezoAllocator.depositBalance() + const assetsToWithdraw = to1e18(2) + const withdrawFee = feeOnRaw(assetsToWithdraw, exitFeeBasisPoints) + const assetsToWithdrawFromMezo = assetsToWithdraw + withdrawFee + + expect(depositBalance).to.be.eq( + firstDepositBalance - assetsToWithdrawFromMezo, + ) + }) + + it("should emit Withdraw event", async () => { + const assetsToWithdraw = to1e18(2) + const sharesToBurn = + to1e18(2) + feeOnRaw(assetsToWithdraw, exitFeeBasisPoints) + + await expect(tx) + .to.emit(stbtc, "Withdraw") + .withArgs( + depositor1.address, + depositor1.address, + depositor1.address, + assetsToWithdraw, + sharesToBurn, + ) + }) + }) + context("when stBTC allocated some of the assets", () => { beforeAfterSnapshotWrapper() From 67c2be5bd9df4b7cdafc5148ac1d7b1ba336b322 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Sat, 20 Apr 2024 12:12:02 +0200 Subject: [PATCH 089/110] Replacing shares and assets partial calculation with feeOnRaw and feeOnTotal functions --- solidity/test/stBTC.test.ts | 53 ++++++++++++++++++++++++++----------- 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/solidity/test/stBTC.test.ts b/solidity/test/stBTC.test.ts index b9a990c82..546e5919a 100644 --- a/solidity/test/stBTC.test.ts +++ b/solidity/test/stBTC.test.ts @@ -531,9 +531,9 @@ describe("stBTC", () => { }) it("depositor 1 should receive shares equal to a deposited amount", async () => { - const expectedShares = await stbtc.previewDeposit( - depositor1AmountToDeposit, - ) + const expectedShares = + depositor1AmountToDeposit - + feeOnTotal(depositor1AmountToDeposit, entryFeeBasisPoints) await expect(depositTx1).to.changeTokenBalances( stbtc, @@ -543,9 +543,9 @@ describe("stBTC", () => { }) it("depositor 2 should receive shares equal to a deposited amount", async () => { - const expectedShares = await stbtc.previewDeposit( - depositor2AmountToDeposit, - ) + const expectedShares = + depositor2AmountToDeposit - + feeOnTotal(depositor2AmountToDeposit, entryFeeBasisPoints) await expect(depositTx2).to.changeTokenBalances( stbtc, @@ -733,7 +733,9 @@ describe("stBTC", () => { before(async () => { minimumDepositAmount = await stbtc.minimumDepositAmount() - const shares = await stbtc.previewDeposit(minimumDepositAmount) + const shares = + minimumDepositAmount - + feeOnTotal(minimumDepositAmount, entryFeeBasisPoints) sharesToMint = shares - 1n await tbtc @@ -773,7 +775,8 @@ describe("stBTC", () => { await tbtc .connect(depositor1) .approve(await stbtc.getAddress(), amountToDeposit) - shares = await stbtc.previewDeposit(amountToDeposit) + shares = + amountToDeposit - feeOnTotal(amountToDeposit, entryFeeBasisPoints) await stbtc .connect(depositor1) .deposit(amountToDeposit, depositor1.address) @@ -839,7 +842,6 @@ describe("stBTC", () => { await stbtc .connect(depositor1) .deposit(firstDeposit, depositor1.address) - await stbtc .connect(depositor1) .deposit(secondDeposit, depositor1.address) @@ -905,7 +907,8 @@ describe("stBTC", () => { }) it("should transfer tBTC back to a depositor1", async () => { - const expectedRedeemedAssets = await stbtc.previewRedeem(to1e18(2)) + const expectedRedeemedAssets = + to1e18(2) - feeOnTotal(to1e18(2), exitFeeBasisPoints) await expect(tx).to.changeTokenBalances( tbtc, [depositor1.address], @@ -914,8 +917,7 @@ describe("stBTC", () => { }) it("should transfer redeem fee to Treasury", async () => { - const assetsToWithdraw = await stbtc.previewRedeem(to1e18(2)) - const redeemFee = feeOnRaw(assetsToWithdraw, exitFeeBasisPoints) + const redeemFee = feeOnTotal(to1e18(2), exitFeeBasisPoints) await expect(tx).to.changeTokenBalances( tbtc, [treasury.address], @@ -925,8 +927,8 @@ describe("stBTC", () => { it("should decrease the deposit balance tracking in Mezo Allocator", async () => { const depositBalance = await mezoAllocator.depositBalance() - const assetsToWithdraw = await stbtc.previewRedeem(to1e18(2)) - const redeemFee = feeOnRaw(assetsToWithdraw, exitFeeBasisPoints) + const redeemFee = feeOnTotal(to1e18(2), exitFeeBasisPoints) + const assetsToWithdraw = to1e18(2) - redeemFee const assetsToWithdrawFromMezo = assetsToWithdraw + redeemFee expect(depositBalance).to.be.eq( @@ -935,7 +937,8 @@ describe("stBTC", () => { }) it("should emit Withdraw event", async () => { - const assetsToWithdraw = await stbtc.previewRedeem(to1e18(2)) + const assetsToWithdraw = + to1e18(2) - feeOnTotal(to1e18(2), exitFeeBasisPoints) await expect(tx) .to.emit(stbtc, "Withdraw") @@ -1374,7 +1377,25 @@ describe("stBTC", () => { }) it("should emit Withdraw event", async () => { - const sharesToBurn = (await stbtc.previewWithdraw(to1e18(2))) + 1n // adjust for rounding + // total assets and total supply right after the deposit of 3 tBTC, before + // the yield and withdrawal. This also includes the entry fee. + // totalAssets() -> 2998500749625187406n + // totalSupply() -> 2998500749625187406n + + // Donate 1 tBTC to stBTC. + // totalAssets() -> 3998500749625187406n (tBTC) + // totalSupply() -> 2998500749625187406n (stBTC) + + // Withdraw 2 tBTC. + // sharesToBurnWithNoFees = 2tBTC * totalAssets() / totalSupply() + // sharesToBurnWithNoFees = 2tBTC * 3998500749625187406n / 2998500749625187406n + const sharesToBurnWithNoFees = 1499812523434570678n + + // Add the withdrawal fee. Adjust for rounding. + const sharesToBurn = + sharesToBurnWithNoFees + + feeOnRaw(sharesToBurnWithNoFees, exitFeeBasisPoints) + + 1n await expect(tx) .to.emit(stbtc, "Withdraw") From 565b662cf9f9ee7b9b213651ae675b6384aa3dba Mon Sep 17 00:00:00 2001 From: Dmitry Date: Mon, 22 Apr 2024 11:52:08 +0200 Subject: [PATCH 090/110] Covering stBTC.totalAssets with tests --- solidity/test/stBTC.test.ts | 101 ++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/solidity/test/stBTC.test.ts b/solidity/test/stBTC.test.ts index 546e5919a..83d461a60 100644 --- a/solidity/test/stBTC.test.ts +++ b/solidity/test/stBTC.test.ts @@ -1938,6 +1938,107 @@ describe("stBTC", () => { }) }) + describe("totalAssets", () => { + beforeAfterSnapshotWrapper() + + const donation = to1e18(1) + const firstDeposit = to1e18(2) + const secondDeposit = to1e18(3) + + context("when there are no deposits", () => { + it("should return 0", async () => { + expect(await stbtc.totalAssets()).to.be.eq(0) + }) + }) + + context("when there are deposits", () => { + context("when there is a first deposit made", () => { + before(async () => { + await tbtc.mint(depositor1.address, firstDeposit) + await tbtc + .connect(depositor1) + .approve(await stbtc.getAddress(), firstDeposit) + await stbtc + .connect(depositor1) + .deposit(firstDeposit, depositor1.address) + }) + + it("should return the total assets", async () => { + const expectedAssets = + firstDeposit - feeOnTotal(firstDeposit, entryFeeBasisPoints) + expect(await stbtc.totalAssets()).to.be.eq(expectedAssets) + }) + }) + + context("when there is a second deposit made", () => { + before(async () => { + await tbtc.mint(depositor1.address, secondDeposit) + await tbtc + .connect(depositor1) + .approve(await stbtc.getAddress(), secondDeposit) + await stbtc + .connect(depositor1) + .deposit(secondDeposit, depositor1.address) + }) + + it("should return the total assets", async () => { + const expectedAssetsFirstDeposit = + firstDeposit - feeOnTotal(firstDeposit, entryFeeBasisPoints) + const expectedAssetsSecondDeposit = + secondDeposit - feeOnTotal(secondDeposit, entryFeeBasisPoints) + expect(await stbtc.totalAssets()).to.be.eq( + expectedAssetsFirstDeposit + expectedAssetsSecondDeposit, + ) + }) + }) + + context("when the funds were allocated", () => { + before(async () => { + await mezoAllocator.connect(maintainer).allocate() + }) + + it("should return the total assets", async () => { + const expectedAssets = await mezoAllocator.depositBalance() + expect(await stbtc.totalAssets()).to.be.eq(expectedAssets) + }) + }) + + context("when there is a donation made", () => { + let totalAssetsBeforeDonation = 0n + + before(async () => { + totalAssetsBeforeDonation = await stbtc.totalAssets() + await tbtc.mint(await stbtc.getAddress(), donation) + }) + + it("should return the total assets", async () => { + expect(await stbtc.totalAssets()).to.be.eq( + totalAssetsBeforeDonation + donation, + ) + }) + }) + + context("when there was a withdrawal", () => { + let totalAssetsBeforeWithdrawal = 0n + + before(async () => { + totalAssetsBeforeWithdrawal = await stbtc.totalAssets() + await stbtc + .connect(depositor1) + .withdraw(to1e18(1), depositor1, depositor1) + }) + + it("should return the total assets", async () => { + const actualWithdrawnAssets = + to1e18(1) + feeOnRaw(to1e18(1), exitFeeBasisPoints) + expect(await stbtc.totalAssets()).to.be.eq( + totalAssetsBeforeWithdrawal - actualWithdrawnAssets, + ) + }) + }) + }) + }) + describe("feeOnTotal - internal test helper", () => { context("when the fee's modulo remainder is greater than 0", () => { it("should add 1 to the result", () => { From 4afd5c17100f3f266deaa662fe2b959f96ce566c Mon Sep 17 00:00:00 2001 From: Dmitry Date: Mon, 22 Apr 2024 12:51:11 +0200 Subject: [PATCH 091/110] Verifying that depositBalance var drives totalAssets() function --- solidity/test/MezoAllocator.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/solidity/test/MezoAllocator.test.ts b/solidity/test/MezoAllocator.test.ts index 23467a497..4e45a09fe 100644 --- a/solidity/test/MezoAllocator.test.ts +++ b/solidity/test/MezoAllocator.test.ts @@ -272,6 +272,11 @@ describe("MezoAllocator", () => { const totalAssets = await mezoAllocator.totalAssets() expect(totalAssets).to.equal(to1e18(5)) }) + + it("should be equal to the deposit balance", async () => { + const depositBalance = await mezoAllocator.depositBalance() + expect(await mezoAllocator.totalAssets()).to.equal(depositBalance) + }) }) }) From 237cb60908aededeab7a27c1f2dacee2fb69bff2 Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Tue, 23 Apr 2024 13:17:50 +0200 Subject: [PATCH 092/110] Update minimum deposit amount for Sepolia BitcoinDepositor defines minimum deposit amount which relates to the tBTC Bridge dust threshold. To simplyfy testing the deposit dust threshold was lowered for Sepolia, we need to align the min deposit amount in BitcoinDepositor too, as this value is enforced in deposit form in the dApp. --- ...itor_update_minimum_deposit_amount copy.ts | 25 +++++++++++++++++++ ...tbtc.ts => 15_update_pause_admin_stbtc.ts} | 0 2 files changed, 25 insertions(+) create mode 100644 solidity/deploy/14_bitcoin_depositor_update_minimum_deposit_amount copy.ts rename solidity/deploy/{14_update_pause_admin_stbtc.ts => 15_update_pause_admin_stbtc.ts} (100%) diff --git a/solidity/deploy/14_bitcoin_depositor_update_minimum_deposit_amount copy.ts b/solidity/deploy/14_bitcoin_depositor_update_minimum_deposit_amount copy.ts new file mode 100644 index 000000000..4657d8c51 --- /dev/null +++ b/solidity/deploy/14_bitcoin_depositor_update_minimum_deposit_amount copy.ts @@ -0,0 +1,25 @@ +import type { HardhatRuntimeEnvironment } from "hardhat/types" +import type { DeployFunction } from "hardhat-deploy/types" + +const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { + const { getNamedAccounts, deployments } = hre + const { deployer } = await getNamedAccounts() + + const minimumDepositAmount = 150000000000000 // 0.00015 tBTC + + await deployments.execute( + "BitcoinDepositor", + { from: deployer, log: true, waitConfirmations: 1 }, + "updateMinDepositAmount", + minimumDepositAmount, + ) +} + +export default func + +func.tags = ["BitcoinDepositorUpdateMinimumDepositAmount"] +func.dependencies = ["BitcoinDepositor"] + +// Run only on Sepolia testnet. +func.skip = async (hre: HardhatRuntimeEnvironment): Promise => + Promise.resolve(hre.network.name !== "sepolia") diff --git a/solidity/deploy/14_update_pause_admin_stbtc.ts b/solidity/deploy/15_update_pause_admin_stbtc.ts similarity index 100% rename from solidity/deploy/14_update_pause_admin_stbtc.ts rename to solidity/deploy/15_update_pause_admin_stbtc.ts From dc481a4e144b43d4da756afc193091c631f14213 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Tue, 23 Apr 2024 15:51:59 +0200 Subject: [PATCH 093/110] Improving tests - Made executions of tests as separate instances not depending on one another - Calculated the expected value instead of fetching from the contract - Replaced assignment with 0n to assigning a type of bigint --- solidity/test/stBTC.test.ts | 59 ++++++++++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 7 deletions(-) diff --git a/solidity/test/stBTC.test.ts b/solidity/test/stBTC.test.ts index 83d461a60..5cd5e5b1f 100644 --- a/solidity/test/stBTC.test.ts +++ b/solidity/test/stBTC.test.ts @@ -1953,6 +1953,8 @@ describe("stBTC", () => { context("when there are deposits", () => { context("when there is a first deposit made", () => { + beforeAfterSnapshotWrapper() + before(async () => { await tbtc.mint(depositor1.address, firstDeposit) await tbtc @@ -1968,14 +1970,25 @@ describe("stBTC", () => { firstDeposit - feeOnTotal(firstDeposit, entryFeeBasisPoints) expect(await stbtc.totalAssets()).to.be.eq(expectedAssets) }) + + it("should be equal to tBTC balance of the contract", async () => { + expect(await stbtc.totalAssets()).to.be.eq( + await tbtc.balanceOf(await stbtc.getAddress()), + ) + }) }) - context("when there is a second deposit made", () => { + context("when there are two deposits made", () => { + beforeAfterSnapshotWrapper() + before(async () => { - await tbtc.mint(depositor1.address, secondDeposit) + await tbtc.mint(depositor1.address, firstDeposit + secondDeposit) await tbtc .connect(depositor1) - .approve(await stbtc.getAddress(), secondDeposit) + .approve(await stbtc.getAddress(), firstDeposit + secondDeposit) + await stbtc + .connect(depositor1) + .deposit(firstDeposit, depositor1.address) await stbtc .connect(depositor1) .deposit(secondDeposit, depositor1.address) @@ -1992,21 +2005,44 @@ describe("stBTC", () => { }) }) - context("when the funds were allocated", () => { + context("when the funds were allocated after deposits", () => { + beforeAfterSnapshotWrapper() + before(async () => { + await tbtc.mint(depositor1.address, firstDeposit + secondDeposit) + await tbtc + .connect(depositor1) + .approve(await stbtc.getAddress(), firstDeposit + secondDeposit) + await stbtc + .connect(depositor1) + .deposit(firstDeposit, depositor1.address) + await stbtc + .connect(depositor1) + .deposit(secondDeposit, depositor1.address) await mezoAllocator.connect(maintainer).allocate() }) it("should return the total assets", async () => { - const expectedAssets = await mezoAllocator.depositBalance() + const deposits = firstDeposit + secondDeposit + const expectedAssets = + deposits - feeOnTotal(deposits, entryFeeBasisPoints) expect(await stbtc.totalAssets()).to.be.eq(expectedAssets) }) }) context("when there is a donation made", () => { - let totalAssetsBeforeDonation = 0n + beforeAfterSnapshotWrapper() + + let totalAssetsBeforeDonation: bigint before(async () => { + await tbtc.mint(depositor1.address, firstDeposit) + await tbtc + .connect(depositor1) + .approve(await stbtc.getAddress(), firstDeposit) + await stbtc + .connect(depositor1) + .deposit(firstDeposit, depositor1.address) totalAssetsBeforeDonation = await stbtc.totalAssets() await tbtc.mint(await stbtc.getAddress(), donation) }) @@ -2019,9 +2055,18 @@ describe("stBTC", () => { }) context("when there was a withdrawal", () => { - let totalAssetsBeforeWithdrawal = 0n + beforeAfterSnapshotWrapper() + + let totalAssetsBeforeWithdrawal: bigint before(async () => { + await tbtc.mint(depositor1.address, firstDeposit) + await tbtc + .connect(depositor1) + .approve(await stbtc.getAddress(), firstDeposit) + await stbtc + .connect(depositor1) + .deposit(firstDeposit, depositor1.address) totalAssetsBeforeWithdrawal = await stbtc.totalAssets() await stbtc .connect(depositor1) From 2e88d5d1d9434849172fbf83dc7bc64f7ed392a2 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Wed, 24 Apr 2024 10:38:24 +0200 Subject: [PATCH 094/110] Reverting ignored deployment dir --- solidity/.gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/solidity/.gitignore b/solidity/.gitignore index 5d20b1efc..1f9e31a2d 100644 --- a/solidity/.gitignore +++ b/solidity/.gitignore @@ -5,4 +5,3 @@ export.json export/ gen/ typechain/ -deployments/ From 718a7234f6d501835a7ca0a322c7b1f6ede822eb Mon Sep 17 00:00:00 2001 From: Dmitry Date: Wed, 24 Apr 2024 10:38:48 +0200 Subject: [PATCH 095/110] Simplifying artifacts fetching for integration tests We can use the '--deploy-fixture' flag to fetch the mainnet artifacts for integration tests purposes. This can replace dealing with the 'integration' flag and using 'getArtifacts' function. --- solidity/deploy/00_resolve_mezo_portal.ts | 10 +++++----- solidity/deploy/00_resolve_tbtc_token.ts | 6 ++---- solidity/deploy/00_resolve_tbtc_vault.ts | 6 +----- solidity/deploy/01_deploy_stbtc.ts | 5 +---- solidity/deploy/02_deploy_mezo_allocator.ts | 8 ++------ solidity/deploy/03_deploy_bitcoin_depositor.ts | 5 +---- solidity/deploy/04_deploy_bitcoin_redeemer.ts | 5 +---- solidity/hardhat.config.ts | 9 --------- solidity/package.json | 2 +- solidity/test/helpers/context.ts | 8 ++------ solidity/test/helpers/contract.ts | 9 +-------- 11 files changed, 17 insertions(+), 56 deletions(-) diff --git a/solidity/deploy/00_resolve_mezo_portal.ts b/solidity/deploy/00_resolve_mezo_portal.ts index 9e1c3fb4e..d67738a8b 100644 --- a/solidity/deploy/00_resolve_mezo_portal.ts +++ b/solidity/deploy/00_resolve_mezo_portal.ts @@ -11,14 +11,14 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { const { log } = deployments const { deployer } = await getNamedAccounts() - let mezoPortal = await deployments.getOrNull("MezoPortal") - if (hre.network.name === "integration") { - mezoPortal = await deployments.getArtifact("MezoPortal") - } + const mezoPortal = await deployments.getOrNull("MezoPortal") if (mezoPortal && isNonZeroAddress(mezoPortal.address)) { log(`using MezoPortal contract at ${mezoPortal.address}`) - } else if ((hre.network.config as HardhatNetworkConfig)?.forking?.enabled) { + } else if ( + hre.network.name === "integration" || + (hre.network.config as HardhatNetworkConfig)?.forking?.enabled + ) { throw new Error("deployed MezoPortal contract not found") } else { log("deploying Mezo Portal contract stub") diff --git a/solidity/deploy/00_resolve_tbtc_token.ts b/solidity/deploy/00_resolve_tbtc_token.ts index 473d77f5d..13343a0b3 100644 --- a/solidity/deploy/00_resolve_tbtc_token.ts +++ b/solidity/deploy/00_resolve_tbtc_token.ts @@ -11,14 +11,12 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { const { log } = deployments const { deployer } = await getNamedAccounts() - let tbtc = await deployments.getOrNull("TBTC") - if (hre.network.name === "integration") { - tbtc = await deployments.getArtifact("TBTC") - } + const tbtc = await deployments.getOrNull("TBTC") if (tbtc && isNonZeroAddress(tbtc.address)) { log(`using TBTC contract at ${tbtc.address}`) } else if ( + hre.network.name === "integration" || !hre.network.tags.allowStubs || (hre.network.config as HardhatNetworkConfig)?.forking?.enabled ) { diff --git a/solidity/deploy/00_resolve_tbtc_vault.ts b/solidity/deploy/00_resolve_tbtc_vault.ts index a946044c6..85ae3bf5a 100644 --- a/solidity/deploy/00_resolve_tbtc_vault.ts +++ b/solidity/deploy/00_resolve_tbtc_vault.ts @@ -23,11 +23,7 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { } else { log("deploying TBTCVault contract stub") - let tbtc = await deployments.getOrNull("TBTC") - if (hre.network.name === "integration") { - tbtc = await deployments.getArtifact("TBTC") - } - + const tbtc = await deployments.get("TBTC") const bridge = await deployments.get("Bridge") const deployment = await deployments.deploy("TBTCVault", { diff --git a/solidity/deploy/01_deploy_stbtc.ts b/solidity/deploy/01_deploy_stbtc.ts index be9afd238..166e2fc4c 100644 --- a/solidity/deploy/01_deploy_stbtc.ts +++ b/solidity/deploy/01_deploy_stbtc.ts @@ -7,10 +7,7 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { const { treasury, governance } = await getNamedAccounts() const { deployer: deployerSigner } = await helpers.signers.getNamedSigners() - let tbtc = await deployments.getOrNull("TBTC") - if (hre.network.name === "integration") { - tbtc = await deployments.getArtifact("TBTC") - } + const tbtc = await deployments.get("TBTC") const [, stbtcDeployment] = await helpers.upgrades.deployProxy("stBTC", { contractName: "stBTC", diff --git a/solidity/deploy/02_deploy_mezo_allocator.ts b/solidity/deploy/02_deploy_mezo_allocator.ts index b3f6d1ef0..2a1bbeb86 100644 --- a/solidity/deploy/02_deploy_mezo_allocator.ts +++ b/solidity/deploy/02_deploy_mezo_allocator.ts @@ -8,12 +8,8 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { const { deployer } = await helpers.signers.getNamedSigners() const stbtc = await deployments.get("stBTC") - let tbtc = await deployments.getOrNull("TBTC") - let mezoPortal = await deployments.getOrNull("MezoPortal") - if (hre.network.name === "integration") { - mezoPortal = await deployments.getArtifact("MezoPortal") - tbtc = await deployments.getArtifact("TBTC") - } + const tbtc = await deployments.get("TBTC") + const mezoPortal = await deployments.get("MezoPortal") const [, deployment] = await helpers.upgrades.deployProxy("MezoAllocator", { factoryOpts: { diff --git a/solidity/deploy/03_deploy_bitcoin_depositor.ts b/solidity/deploy/03_deploy_bitcoin_depositor.ts index cade3cbf1..af280c9f5 100644 --- a/solidity/deploy/03_deploy_bitcoin_depositor.ts +++ b/solidity/deploy/03_deploy_bitcoin_depositor.ts @@ -7,10 +7,7 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { const { governance } = await getNamedAccounts() const { deployer } = await helpers.signers.getNamedSigners() - let tbtc = await deployments.getOrNull("TBTC") - if (hre.network.name === "integration") { - tbtc = await deployments.getArtifact("TBTC") - } + const tbtc = await deployments.get("TBTC") const bridge = await deployments.get("Bridge") const tbtcVault = await deployments.get("TBTCVault") const stbtc = await deployments.get("stBTC") diff --git a/solidity/deploy/04_deploy_bitcoin_redeemer.ts b/solidity/deploy/04_deploy_bitcoin_redeemer.ts index 96a0d0312..7dbc0d847 100644 --- a/solidity/deploy/04_deploy_bitcoin_redeemer.ts +++ b/solidity/deploy/04_deploy_bitcoin_redeemer.ts @@ -6,10 +6,7 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { const { deployments, helpers } = hre const { deployer } = await helpers.signers.getNamedSigners() - let tbtc = await deployments.getOrNull("TBTC") - if (hre.network.name === "integration") { - tbtc = await deployments.getArtifact("TBTC") - } + const tbtc = await deployments.get("TBTC") const stbtc = await deployments.get("stBTC") const tbtcVault = await deployments.get("TBTCVault") diff --git a/solidity/hardhat.config.ts b/solidity/hardhat.config.ts index 1e52823fa..c72c798e2 100644 --- a/solidity/hardhat.config.ts +++ b/solidity/hardhat.config.ts @@ -31,7 +31,6 @@ const config: HardhatUserConfig = { }, integration: { url: "http://localhost:8545", - tags: ["allowStubs"], }, sepolia: { url: process.env.CHAIN_API_URL || "", @@ -52,14 +51,6 @@ const config: HardhatUserConfig = { }, external: { - contracts: - process.env.INTEGRATION_TEST === "true" - ? [ - { - artifacts: "./external/mainnet", - }, - ] - : undefined, deployments: { sepolia: ["./external/sepolia"], mainnet: ["./external/mainnet"], diff --git a/solidity/package.json b/solidity/package.json index 7809a84cc..180773092 100644 --- a/solidity/package.json +++ b/solidity/package.json @@ -27,7 +27,7 @@ "lint:config": "prettier --check '**/*.@(json)'", "lint:config:fix": "prettier --write '**/*.@(json)'", "test": "hardhat test ./test/*.test.ts", - "test:integration": "INTEGRATION_TEST=true hardhat test ./test/integration/*.test.ts --network integration" + "test:integration": "hardhat test --deploy-fixture ./test/integration/*.test.ts --network integration" }, "devDependencies": { "@keep-network/hardhat-helpers": "^0.7.1", diff --git a/solidity/test/helpers/context.ts b/solidity/test/helpers/context.ts index 9a9f223dd..ea8bb6920 100644 --- a/solidity/test/helpers/context.ts +++ b/solidity/test/helpers/context.ts @@ -14,7 +14,6 @@ import type { // eslint-disable-next-line import/prefer-default-export export async function deployment() { - const isIntegration = deployments.getNetworkName() === "integration" await deployments.fixture() const stbtc: stBTC = await getDeployedContract("stBTC") @@ -23,16 +22,13 @@ export async function deployment() { const bitcoinRedeemer: BitcoinRedeemer = await getDeployedContract("BitcoinRedeemer") - const tbtc: TestTBTC = await getDeployedContract("TBTC", isIntegration) + const tbtc: TestTBTC = await getDeployedContract("TBTC") const tbtcBridge: BridgeStub = await getDeployedContract("Bridge") const tbtcVault: TBTCVaultStub = await getDeployedContract("TBTCVault") const mezoAllocator: MezoAllocator = await getDeployedContract("MezoAllocator") - const mezoPortal: IMezoPortal = await getDeployedContract( - "MezoPortal", - isIntegration, - ) + const mezoPortal: IMezoPortal = await getDeployedContract("MezoPortal") return { tbtc, diff --git a/solidity/test/helpers/contract.ts b/solidity/test/helpers/contract.ts index be944e984..5ff70126b 100644 --- a/solidity/test/helpers/contract.ts +++ b/solidity/test/helpers/contract.ts @@ -12,15 +12,8 @@ const { getUnnamedSigners } = helpers.signers // eslint-disable-next-line import/prefer-default-export export async function getDeployedContract( deploymentName: string, - isIntegrationTest: boolean = false, ): Promise { - let address: string - let abi: string - if (isIntegrationTest) { - ;({ address, abi } = await deployments.getArtifact(deploymentName)) - } else { - ;({ address, abi } = await deployments.get(deploymentName)) - } + const { address, abi } = await deployments.get(deploymentName) // Use default unnamed signer from index 0 to initialize the contract runner. const [defaultSigner] = await getUnnamedSigners() From 0a2a2d84ebfd0b01a58d01f7dc1ca91c2c292612 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Wed, 24 Apr 2024 10:46:25 +0200 Subject: [PATCH 096/110] Adding README explaining how to run the integration tests --- solidity/README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/solidity/README.md b/solidity/README.md index 651236aa9..177801d40 100644 --- a/solidity/README.md +++ b/solidity/README.md @@ -24,6 +24,22 @@ To run the test execute: $ pnpm test ``` +### Integration testing + +To run the integration tests follow these steps: + +- Run the Hardhat Node locally forking Mainnet at block `19680873`: + +``` +$ npx hardhat node --no-deploy --fork https://eth-mainnet.g.alchemy.com/v2/ --fork-block-number 19680873 +``` + +- Once the local node is running you can execute the integration tests: + +``` +$ pnpm test:integration +``` + ### Deploying We deploy our contracts with From 32062d6cb6a02877a70eb546c10a78290b9a7862 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Wed, 24 Apr 2024 12:32:22 +0200 Subject: [PATCH 097/110] Reverting 'deployment' command back to 'deploy' Instead of running 'pnpm deploy', you should run 'pnpm run deploy' to bypass the conflict between a custom hardhat command and a build-in pnpm command. --- .github/workflows/solidity.yaml | 2 +- solidity/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/solidity.yaml b/.github/workflows/solidity.yaml index 818e93d59..7586edb1a 100644 --- a/.github/workflows/solidity.yaml +++ b/.github/workflows/solidity.yaml @@ -140,7 +140,7 @@ jobs: path: solidity/ - name: Deploy - run: pnpm run deployment --no-compile + run: pnpm run deploy --no-compile solidity-deploy-testnet: needs: [solidity-deploy-dry-run] diff --git a/solidity/package.json b/solidity/package.json index 180773092..8cb5969e1 100644 --- a/solidity/package.json +++ b/solidity/package.json @@ -16,7 +16,7 @@ "scripts": { "clean": "hardhat clean && rm -rf cache/ export/ gen/ export.json", "build": "hardhat compile", - "deployment": "hardhat deploy --export export.json", + "deploy": "hardhat deploy --export export.json", "docs": "hardhat docgen", "format": "npm run lint:js && npm run lint:sol && npm run lint:config", "format:fix": "npm run lint:js:fix && npm run lint:sol:fix && npm run lint:config:fix", From 962d17355f35fa949968a51405204a84199006f6 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Wed, 24 Apr 2024 13:59:22 +0200 Subject: [PATCH 098/110] Simplifying the way we check for network names in the deployment scripts We use stubs only in hardhat network. For all other networks we'd use actual contracts. This way the deployment scripts can be simplified. --- solidity/deploy/00_resolve_mezo_portal.ts | 10 ++-------- solidity/deploy/00_resolve_tbtc_bridge.ts | 7 ++----- solidity/deploy/00_resolve_tbtc_token.ts | 11 ++--------- solidity/deploy/00_resolve_tbtc_vault.ts | 24 ++++++++--------------- solidity/hardhat.config.ts | 3 --- 5 files changed, 14 insertions(+), 41 deletions(-) diff --git a/solidity/deploy/00_resolve_mezo_portal.ts b/solidity/deploy/00_resolve_mezo_portal.ts index d67738a8b..15569002a 100644 --- a/solidity/deploy/00_resolve_mezo_portal.ts +++ b/solidity/deploy/00_resolve_mezo_portal.ts @@ -1,8 +1,5 @@ import type { DeployFunction } from "hardhat-deploy/types" -import type { - HardhatNetworkConfig, - HardhatRuntimeEnvironment, -} from "hardhat/types" +import type { HardhatRuntimeEnvironment } from "hardhat/types" import { isNonZeroAddress } from "../helpers/address" import { waitConfirmationsNumber } from "../helpers/deployment" @@ -15,10 +12,7 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { if (mezoPortal && isNonZeroAddress(mezoPortal.address)) { log(`using MezoPortal contract at ${mezoPortal.address}`) - } else if ( - hre.network.name === "integration" || - (hre.network.config as HardhatNetworkConfig)?.forking?.enabled - ) { + } else if (hre.network.name !== "hardhat") { throw new Error("deployed MezoPortal contract not found") } else { log("deploying Mezo Portal contract stub") diff --git a/solidity/deploy/00_resolve_tbtc_bridge.ts b/solidity/deploy/00_resolve_tbtc_bridge.ts index 4150b696a..98e60c54e 100644 --- a/solidity/deploy/00_resolve_tbtc_bridge.ts +++ b/solidity/deploy/00_resolve_tbtc_bridge.ts @@ -1,8 +1,5 @@ import type { DeployFunction } from "hardhat-deploy/types" -import type { - HardhatNetworkConfig, - HardhatRuntimeEnvironment, -} from "hardhat/types" +import type { HardhatRuntimeEnvironment } from "hardhat/types" import { isNonZeroAddress } from "../helpers/address" import { waitConfirmationsNumber } from "../helpers/deployment" @@ -15,7 +12,7 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { if (bridge && isNonZeroAddress(bridge.address)) { log(`using Bridge contract at ${bridge.address}`) - } else if ((hre.network.config as HardhatNetworkConfig)?.forking?.enabled) { + } else if (hre.network.name !== "hardhat") { throw new Error("deployed Bridge contract not found") } else { log("deploying Bridge contract stub") diff --git a/solidity/deploy/00_resolve_tbtc_token.ts b/solidity/deploy/00_resolve_tbtc_token.ts index 13343a0b3..e710fd02a 100644 --- a/solidity/deploy/00_resolve_tbtc_token.ts +++ b/solidity/deploy/00_resolve_tbtc_token.ts @@ -1,8 +1,5 @@ import type { DeployFunction } from "hardhat-deploy/types" -import type { - HardhatNetworkConfig, - HardhatRuntimeEnvironment, -} from "hardhat/types" +import type { HardhatRuntimeEnvironment } from "hardhat/types" import { isNonZeroAddress } from "../helpers/address" import { waitConfirmationsNumber } from "../helpers/deployment" @@ -15,11 +12,7 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { if (tbtc && isNonZeroAddress(tbtc.address)) { log(`using TBTC contract at ${tbtc.address}`) - } else if ( - hre.network.name === "integration" || - !hre.network.tags.allowStubs || - (hre.network.config as HardhatNetworkConfig)?.forking?.enabled - ) { + } else if (hre.network.name !== "hardhat") { throw new Error("deployed TBTC contract not found") } else { log("deploying TBTC contract stub") diff --git a/solidity/deploy/00_resolve_tbtc_vault.ts b/solidity/deploy/00_resolve_tbtc_vault.ts index 85ae3bf5a..c8a0f5517 100644 --- a/solidity/deploy/00_resolve_tbtc_vault.ts +++ b/solidity/deploy/00_resolve_tbtc_vault.ts @@ -1,8 +1,5 @@ import type { DeployFunction } from "hardhat-deploy/types" -import type { - HardhatNetworkConfig, - HardhatRuntimeEnvironment, -} from "hardhat/types" +import type { HardhatRuntimeEnvironment } from "hardhat/types" import { isNonZeroAddress } from "../helpers/address" import { waitConfirmationsNumber } from "../helpers/deployment" @@ -15,10 +12,7 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { if (tbtcVault && isNonZeroAddress(tbtcVault.address)) { log(`using TBTCVault contract at ${tbtcVault.address}`) - } else if ( - !hre.network.tags.allowStubs || - (hre.network.config as HardhatNetworkConfig)?.forking?.enabled - ) { + } else if (hre.network.name !== "hardhat") { throw new Error("deployed TBTCVault contract not found") } else { log("deploying TBTCVault contract stub") @@ -34,14 +28,12 @@ const func: DeployFunction = async (hre: HardhatRuntimeEnvironment) => { waitConfirmations: waitConfirmationsNumber(hre), }) - if (hre.network.name === "hardhat") { - await deployments.execute( - "TBTC", - { from: deployer, log: true }, - "setOwner", - deployment.address, - ) - } + await deployments.execute( + "TBTC", + { from: deployer, log: true }, + "setOwner", + deployment.address, + ) } } diff --git a/solidity/hardhat.config.ts b/solidity/hardhat.config.ts index c72c798e2..ac6a1492e 100644 --- a/solidity/hardhat.config.ts +++ b/solidity/hardhat.config.ts @@ -26,9 +26,6 @@ const config: HardhatUserConfig = { }, networks: { - hardhat: { - tags: ["allowStubs"], - }, integration: { url: "http://localhost:8545", }, From bfe755c788ec7e1aeecc3583ecac131a2dbef7aa Mon Sep 17 00:00:00 2001 From: Dmitry Date: Wed, 24 Apr 2024 14:08:23 +0200 Subject: [PATCH 099/110] Importing ethers from HH to make eslint happy --- solidity/test/integration/MezoAllocator.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/solidity/test/integration/MezoAllocator.test.ts b/solidity/test/integration/MezoAllocator.test.ts index 127d3db2e..62f4b0d27 100644 --- a/solidity/test/integration/MezoAllocator.test.ts +++ b/solidity/test/integration/MezoAllocator.test.ts @@ -1,4 +1,4 @@ -import { helpers } from "hardhat" +import { helpers, ethers } from "hardhat" import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers" import { expect } from "chai" import { loadFixture } from "@nomicfoundation/hardhat-toolbox/network-helpers" @@ -63,7 +63,6 @@ describe("MezoAllocator", () => { } = await loadFixture(fixture)) await impersonateAccount(whaleAddress) - // eslint-disable-next-line tbtcHolder = await ethers.getSigner(whaleAddress) }) From e22155407aef72bddc27df6ebd2fd2cb99c09217 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Wed, 24 Apr 2024 14:12:31 +0200 Subject: [PATCH 100/110] Rephrasing the comment for a test --- solidity/test/integration/MezoAllocator.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/solidity/test/integration/MezoAllocator.test.ts b/solidity/test/integration/MezoAllocator.test.ts index 62f4b0d27..a700dc4f4 100644 --- a/solidity/test/integration/MezoAllocator.test.ts +++ b/solidity/test/integration/MezoAllocator.test.ts @@ -104,7 +104,7 @@ describe("MezoAllocator", () => { it("should increment the deposit id", async () => { const actualDepositId = await mezoAllocator.depositId() - // As of writing this test, the deposit id was 2272 before the new + // As of a forked block 19680873, the deposit id was 2272 before the new // allocation. The deposit id should be incremented by 1. expect(actualDepositId).to.equal(2273) }) From 8c941459469311e8cf22189ae9303c1c654305cf Mon Sep 17 00:00:00 2001 From: Dmitry Date: Wed, 24 Apr 2024 15:48:03 +0200 Subject: [PATCH 101/110] Making withdrawal tests independent from each other --- .../test/integration/MezoAllocator.test.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/solidity/test/integration/MezoAllocator.test.ts b/solidity/test/integration/MezoAllocator.test.ts index a700dc4f4..4f2f94ea8 100644 --- a/solidity/test/integration/MezoAllocator.test.ts +++ b/solidity/test/integration/MezoAllocator.test.ts @@ -182,6 +182,8 @@ describe("MezoAllocator", () => { context("when the caller is stBTC contract", () => { context("when there is no deposit", () => { + beforeAfterSnapshotWrapper() + it("should revert", async () => { // It is reverted because deposit Id is 0 and there is no deposit // with id 0 in Mezo Portal for Acre. Mezo Portal reverts with the @@ -192,6 +194,8 @@ describe("MezoAllocator", () => { }) context("when there is a deposit", () => { + beforeAfterSnapshotWrapper() + let tx: ContractTransactionResponse before(async () => { @@ -202,6 +206,8 @@ describe("MezoAllocator", () => { }) context("when the deposit is not fully withdrawn", () => { + beforeAfterSnapshotWrapper() + before(async () => { tx = await stbtc.withdraw(to1e18(2), depositor, depositor) }) @@ -235,22 +241,24 @@ describe("MezoAllocator", () => { }) context("when the deposit is fully withdrawn", () => { + beforeAfterSnapshotWrapper() + before(async () => { - tx = await stbtc.withdraw(to1e18(3), depositor, depositor) + tx = await stbtc.withdraw(to1e18(5), depositor, depositor) }) - it("should transfer 3 tBTC back to a depositor", async () => { + it("should transfer 5 tBTC back to a depositor", async () => { await expect(tx).to.changeTokenBalances( tbtc, [depositor.address], - [to1e18(3)], + [to1e18(5)], ) }) it("should emit DepositWithdrawn event", async () => { await expect(tx) .to.emit(mezoAllocator, "DepositWithdrawn") - .withArgs(2273, to1e18(3)) + .withArgs(2273, to1e18(5)) }) it("should decrease tracked deposit balance amount to zero", async () => { @@ -262,7 +270,7 @@ describe("MezoAllocator", () => { await expect(tx).to.changeTokenBalances( tbtc, [await mezoPortal.getAddress()], - [-to1e18(3)], + [-to1e18(5)], ) }) }) From f68e51f620dc1b4ed5b62cbbc1e3704a65845c41 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Thu, 25 Apr 2024 10:47:28 +0200 Subject: [PATCH 102/110] Covering a scenario when withdrawing more than deposited Verified that MezoPortal will throw an InsufficientDepositAmount error when a depositor wants to withdraw more than was initially deposited. --- solidity/test/integration/MezoAllocator.test.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/solidity/test/integration/MezoAllocator.test.ts b/solidity/test/integration/MezoAllocator.test.ts index 4f2f94ea8..1840815b2 100644 --- a/solidity/test/integration/MezoAllocator.test.ts +++ b/solidity/test/integration/MezoAllocator.test.ts @@ -274,6 +274,19 @@ describe("MezoAllocator", () => { ) }) }) + + context("when withdrawing more than was deposited", () => { + beforeAfterSnapshotWrapper() + + it("should revert", async () => { + await expect(stbtc.withdraw(to1e18(6), depositor, depositor)) + .to.be.revertedWithCustomError( + mezoPortal, + "InsufficientDepositAmount", + ) + .withArgs(to1e18(6), to1e18(5)) + }) + }) }) }) }) From 90f1e642f8bfb4a151f95bb2a48213bcb2391b20 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Thu, 25 Apr 2024 11:56:16 +0200 Subject: [PATCH 103/110] Changing a generic error to verify against a custom error DepositNotFound --- solidity/test/integration/MezoAllocator.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/solidity/test/integration/MezoAllocator.test.ts b/solidity/test/integration/MezoAllocator.test.ts index 1840815b2..758704827 100644 --- a/solidity/test/integration/MezoAllocator.test.ts +++ b/solidity/test/integration/MezoAllocator.test.ts @@ -185,11 +185,11 @@ describe("MezoAllocator", () => { beforeAfterSnapshotWrapper() it("should revert", async () => { - // It is reverted because deposit Id is 0 and there is no deposit - // with id 0 in Mezo Portal for Acre. Mezo Portal reverts with the - // "unrecognized custom error" that is why we verify only against - // a generic revert. - await expect(stbtc.withdraw(1n, depositor, depositor)).to.be.reverted + // It is reverted because deposit id is 0 and there is no deposit + // with id 0 in Mezo Portal for Acre. + await expect( + stbtc.withdraw(1n, depositor, depositor), + ).to.be.revertedWithCustomError(mezoPortal, "DepositNotFound") }) }) From 704abf3224461d2af4572e80d3d67aaf1010fcba Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Thu, 25 Apr 2024 12:08:47 +0200 Subject: [PATCH 104/110] Wrap node forking command for integration tests To simplify running the hardhat node for integration tests we defined hardhat network in hardhat config file and a command to run the node with `pnpm run node:forking`. --- solidity/README.md | 6 ++++-- solidity/hardhat.config.ts | 6 ++++++ solidity/package.json | 1 + 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/solidity/README.md b/solidity/README.md index 177801d40..1b239660a 100644 --- a/solidity/README.md +++ b/solidity/README.md @@ -28,10 +28,12 @@ $ pnpm test To run the integration tests follow these steps: -- Run the Hardhat Node locally forking Mainnet at block `19680873`: +- Define `CHAIN_API_URL` environment variable pointing to Ethereum Mainnet RPC URL. + +- Run the Hardhat Node locally forking Mainnet: ``` -$ npx hardhat node --no-deploy --fork https://eth-mainnet.g.alchemy.com/v2/ --fork-block-number 19680873 +$ pnpm run node:forking ``` - Once the local node is running you can execute the integration tests: diff --git a/solidity/hardhat.config.ts b/solidity/hardhat.config.ts index ac6a1492e..e1e2fae22 100644 --- a/solidity/hardhat.config.ts +++ b/solidity/hardhat.config.ts @@ -26,6 +26,12 @@ const config: HardhatUserConfig = { }, networks: { + hardhat: { + forking: + process.env.FORKING === "true" + ? { url: process.env.CHAIN_API_URL ?? "", blockNumber: 19680873 } + : undefined, + }, integration: { url: "http://localhost:8545", }, diff --git a/solidity/package.json b/solidity/package.json index 8cb5969e1..7c0d995b7 100644 --- a/solidity/package.json +++ b/solidity/package.json @@ -26,6 +26,7 @@ "lint:sol:fix": "solhint 'contracts/**/*.sol' --fix && prettier --write 'contracts/**/*.sol'", "lint:config": "prettier --check '**/*.@(json)'", "lint:config:fix": "prettier --write '**/*.@(json)'", + "node:forking": "FORKING=true hardhat node --no-deploy", "test": "hardhat test ./test/*.test.ts", "test:integration": "hardhat test --deploy-fixture ./test/integration/*.test.ts --network integration" }, From 5d997328def4e873b7657fad499361d9fa354809 Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Thu, 25 Apr 2024 12:15:28 +0200 Subject: [PATCH 105/110] Define env variables with dotenv-safer We redefined env variables handling to use dotenv-safer and separate variables for environments. It is expected that developer on local environment copies the .env.example as .env file. --- .github/workflows/solidity.yaml | 4 ++-- .gitignore | 2 ++ pnpm-lock.yaml | 11 +++++++++ solidity/.env | 4 ---- solidity/.env.ci.example | 1 + solidity/.env.example | 9 +++++-- solidity/hardhat.config.ts | 42 +++++++++++++++++++++++---------- solidity/package.json | 1 + 8 files changed, 54 insertions(+), 20 deletions(-) delete mode 100644 solidity/.env create mode 100644 solidity/.env.ci.example diff --git a/.github/workflows/solidity.yaml b/.github/workflows/solidity.yaml index 7586edb1a..5765f374a 100644 --- a/.github/workflows/solidity.yaml +++ b/.github/workflows/solidity.yaml @@ -172,8 +172,8 @@ jobs: - name: Deploy contracts env: - ACCOUNTS_PRIVATE_KEYS: ${{ secrets.TESTNET_ETH_CONTRACT_OWNER_PRIVATE_KEY }} - CHAIN_API_URL: ${{ secrets.SEPOLIA_CHAIN_API_URL }} + SEPOLIA_PRIVATE_KEY: ${{ secrets.TESTNET_ETH_CONTRACT_OWNER_PRIVATE_KEY }} + SEPOLIA_RPC_URL: ${{ secrets.SEPOLIA_CHAIN_API_URL }} ETHERSCAN_API_KEY: ${{ secrets.ETHERSCAN_API_KEY }} run: | pnpm run deploy --network ${{ github.event.inputs.environment }} diff --git a/.gitignore b/.gitignore index 629d01034..022d1e746 100644 --- a/.gitignore +++ b/.gitignore @@ -13,5 +13,7 @@ tmp/ # Environment configuration files .envrc +.env .env.* !.env.example +!.env.ci.example diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 307077ecd..da6eba6e3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -242,6 +242,9 @@ importers: chai: specifier: ^4.3.10 version: 4.3.10 + dotenv-safer: + specifier: ^1.0.0 + version: 1.0.0(dotenv@8.6.0) eslint: specifier: ^8.54.0 version: 8.54.0 @@ -10703,6 +10706,14 @@ packages: /dotenv-expand@5.1.0: resolution: {integrity: sha512-YXQl1DSa4/PQyRfgrv6aoNjhasp/p4qs9FjJ4q4cQk+8m4r6k4ZSiEyytKG8f8W9gi8WsQtIObNmKd+tMzNTmA==} + /dotenv-safer@1.0.0(dotenv@8.6.0): + resolution: {integrity: sha512-QzRM3UrtdWn9iYJ4rgd1zPwSb1PjYVTpkWk0KVCdwZkatbonwGDuuKkw+lwXGTVAMGN/uVDs0HfOgxrBqlwElQ==} + peerDependencies: + dotenv: '>= 8.2.0' + dependencies: + dotenv: 8.6.0 + dev: true + /dotenv@7.0.0: resolution: {integrity: sha512-M3NhsLbV1i6HuGzBUH8vXrtxOk+tWmzWKDMbAVSUp3Zsjm7ywFeuwrUXhmhQyRK1q5B5GGy7hcXPbj3bnfZg2g==} engines: {node: '>=6'} diff --git a/solidity/.env b/solidity/.env deleted file mode 100644 index aea8b0315..000000000 --- a/solidity/.env +++ /dev/null @@ -1,4 +0,0 @@ -CHAIN_API_URL=${CHAIN_API_URL} -ACCOUNTS_PRIVATE_KEYS=${ACCOUNTS_PRIVATE_KEYS} -ETHERSCAN_API_KEY=${ETHERSCAN_API_KEY} -COINMARKETCAP_API_KEY=${COINMARKETCAP_API_KEY} diff --git a/solidity/.env.ci.example b/solidity/.env.ci.example new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/solidity/.env.ci.example @@ -0,0 +1 @@ + diff --git a/solidity/.env.example b/solidity/.env.example index 9cba5dee7..ebcf14fb0 100644 --- a/solidity/.env.example +++ b/solidity/.env.example @@ -1,4 +1,9 @@ -CHAIN_API_URL= -ACCOUNTS_PRIVATE_KEYS= +MAINNET_RPC_URL= +MAINNET_PRIVATE_KEY= + +SEPOLIA_RPC_URL= +SEPOLIA_PRIVATE_KEY= + ETHERSCAN_API_KEY= + COINMARKETCAP_API_KEY= diff --git a/solidity/hardhat.config.ts b/solidity/hardhat.config.ts index e1e2fae22..71cddc5e2 100644 --- a/solidity/hardhat.config.ts +++ b/solidity/hardhat.config.ts @@ -5,6 +5,28 @@ import "hardhat-contract-sizer" import "hardhat-deploy" import "solidity-docgen" import "@keep-network/hardhat-helpers" +import dotenv from "dotenv-safer" + +dotenv.config({ + allowEmptyValues: true, + example: process.env.CI ? ".env.ci.example" : ".env.example", +}) + +const MAINNET_RPC_URL = process.env.MAINNET_RPC_URL ?? "" + +const MAINNET_PRIVATE_KEY = process.env.MAINNET_PRIVATE_KEY + ? [process.env.MAINNET_PRIVATE_KEY] + : [] + +const SEPOLIA_RPC_URL = process.env.SEPOLIA_RPC_URL ?? "" + +const SEPOLIA_PRIVATE_KEY = process.env.SEPOLIA_PRIVATE_KEY + ? [process.env.SEPOLIA_PRIVATE_KEY] + : [] + +const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY ?? "" + +const COINMARKETCAP_API_KEY = process.env.COINMARKETCAP_API_KEY ?? "" const config: HardhatUserConfig = { solidity: { @@ -29,26 +51,22 @@ const config: HardhatUserConfig = { hardhat: { forking: process.env.FORKING === "true" - ? { url: process.env.CHAIN_API_URL ?? "", blockNumber: 19680873 } + ? { url: MAINNET_RPC_URL, blockNumber: 19680873 } : undefined, }, integration: { url: "http://localhost:8545", }, sepolia: { - url: process.env.CHAIN_API_URL || "", + url: SEPOLIA_RPC_URL, chainId: 11155111, - accounts: process.env.ACCOUNTS_PRIVATE_KEYS - ? process.env.ACCOUNTS_PRIVATE_KEYS.split(",") - : undefined, + accounts: SEPOLIA_PRIVATE_KEY, tags: ["etherscan"], }, mainnet: { - url: process.env.CHAIN_API_URL || "", + url: MAINNET_RPC_URL, chainId: 1, - accounts: process.env.ACCOUNTS_PRIVATE_KEYS - ? process.env.ACCOUNTS_PRIVATE_KEYS.split(",") - : undefined, + accounts: MAINNET_PRIVATE_KEY, tags: ["etherscan"], }, }, @@ -63,8 +81,8 @@ const config: HardhatUserConfig = { etherscan: { apiKey: { - sepolia: process.env.ETHERSCAN_API_KEY, - mainnet: process.env.ETHERSCAN_API_KEY, + sepolia: ETHERSCAN_API_KEY, + mainnet: ETHERSCAN_API_KEY, }, }, @@ -104,7 +122,7 @@ const config: HardhatUserConfig = { gasReporter: { enabled: true, - coinmarketcap: process.env.COINMARKETCAP_API_KEY, + coinmarketcap: COINMARKETCAP_API_KEY, }, typechain: { diff --git a/solidity/package.json b/solidity/package.json index 7c0d995b7..7adee5546 100644 --- a/solidity/package.json +++ b/solidity/package.json @@ -46,6 +46,7 @@ "@types/mocha": "^10.0.6", "@types/node": "^20.9.4", "chai": "^4.3.10", + "dotenv-safer": "^1.0.0", "eslint": "^8.54.0", "ethers": "^6.8.1", "hardhat": "^2.19.1", From e81a5d20d7c094468f3fe01744fcdd60cfe22771 Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Thu, 25 Apr 2024 12:34:45 +0200 Subject: [PATCH 106/110] Prepare env file before running hardhat scripts Before running the hardhat scripts the prepare script will ensure the `.env` file is available, if not it will be created from the example. --- solidity/package.json | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/solidity/package.json b/solidity/package.json index 7adee5546..b34e4bbc9 100644 --- a/solidity/package.json +++ b/solidity/package.json @@ -15,9 +15,10 @@ ], "scripts": { "clean": "hardhat clean && rm -rf cache/ export/ gen/ export.json", - "build": "hardhat compile", - "deploy": "hardhat deploy --export export.json", - "docs": "hardhat docgen", + "prepare:env": "cp -n .env.example .env || true", + "build": "npm run prepare:env && hardhat compile", + "deploy": "npm run prepare:env && hardhat deploy --export export.json", + "docs": "npm run prepare:env && hardhat docgen", "format": "npm run lint:js && npm run lint:sol && npm run lint:config", "format:fix": "npm run lint:js:fix && npm run lint:sol:fix && npm run lint:config:fix", "lint:js": "eslint .", @@ -27,7 +28,7 @@ "lint:config": "prettier --check '**/*.@(json)'", "lint:config:fix": "prettier --write '**/*.@(json)'", "node:forking": "FORKING=true hardhat node --no-deploy", - "test": "hardhat test ./test/*.test.ts", + "test": "npm run prepare:env && hardhat test ./test/*.test.ts", "test:integration": "hardhat test --deploy-fixture ./test/integration/*.test.ts --network integration" }, "devDependencies": { From cd5a16969466c29e8dbb01d3724a2da6bbb7811b Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Thu, 25 Apr 2024 14:36:54 +0200 Subject: [PATCH 107/110] Declare types for dotenv-safer We need to declare types to fix eslint problems: ``` /home/runner/work/acre/acre/solidity/hardhat.config.ts Error: 10:1 error Unsafe call of an `any` typed value @typescript-eslint/no-unsafe-call Error: 10:8 error Unsafe member access .config on an `any` value @typescript-eslint/no-unsafe-member-access ``` --- solidity/types/dotenv-safer.d.ts | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 solidity/types/dotenv-safer.d.ts diff --git a/solidity/types/dotenv-safer.d.ts b/solidity/types/dotenv-safer.d.ts new file mode 100644 index 000000000..2d2867330 --- /dev/null +++ b/solidity/types/dotenv-safer.d.ts @@ -0,0 +1,4 @@ +declare module "dotenv-safer" { + // eslint-disable-next-line import/prefer-default-export + export function config(options = {}) +} From 94e2266eadd23133ef2b91c08f14510e8d7d6145 Mon Sep 17 00:00:00 2001 From: Jakub Nowakowski Date: Thu, 25 Apr 2024 15:18:18 +0200 Subject: [PATCH 108/110] Update CHAIN_API_URL in README.md --- solidity/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/solidity/README.md b/solidity/README.md index 1b239660a..e842e5564 100644 --- a/solidity/README.md +++ b/solidity/README.md @@ -28,7 +28,7 @@ $ pnpm test To run the integration tests follow these steps: -- Define `CHAIN_API_URL` environment variable pointing to Ethereum Mainnet RPC URL. +- Define `MAINNET_RPC_URL` environment variable pointing to Ethereum Mainnet RPC URL. - Run the Hardhat Node locally forking Mainnet: From d215daa6da1a465f5eb3f287f15ff5ec9a540107 Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Thu, 25 Apr 2024 15:24:39 +0200 Subject: [PATCH 109/110] Fix `calculateDepositFee` in `BitcoinDepositor` Fix the `calculateDepositFee` in Ethereum implementation of `BitcoinDepositor`: - add missing `runner` when creating the ethers Contract instance for Birdge and Vault contract. To call the contract methods we need to pass runner which is generally ethers signer or provider, - fix typo in contract's function name `depositsParameters` -> `depositParameters`. --- sdk/src/lib/ethereum/bitcoin-depositor.ts | 22 ++++++++++++-------- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 20 +++++++++++------- 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index 52f634c24..98e9fa14d 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -208,21 +208,25 @@ class EthereumBitcoinDepositor } const bridgeAddress = await this.instance.bridge() - const bridge = new Contract(bridgeAddress, [ - "function depositsParameters()", - ]) - const depositsParameters = - (await bridge.depositsParameters()) as TbtcDepositParameters + const bridge = new Contract( + bridgeAddress, + ["function depositParameters()"], + this.instance.runner, + ) + const depositParameters = + (await bridge.depositParameters()) as TbtcDepositParameters const vaultAddress = await this.getTbtcVaultChainIdentifier() - const vault = new Contract(`0x${vaultAddress.identifierHex}`, [ - "function optimisticMintingFeeDivisor()", - ]) + const vault = new Contract( + `0x${vaultAddress.identifierHex}`, + ["function optimisticMintingFeeDivisor()"], + this.instance.runner, + ) const optimisticMintingFeeDivisor = (await vault.optimisticMintingFeeDivisor()) as bigint this.#cache.tbtcBridgeMintingParameters = { - ...depositsParameters, + ...depositParameters, optimisticMintingFeeDivisor, } return this.#cache.tbtcBridgeMintingParameters diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index 882ea534a..527188b48 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -25,6 +25,7 @@ const testData = { describe("BitcoinDepositor", () => { const spyOnEthersDataSlice = jest.spyOn(ethers, "dataSlice") const spyOnEthersContract = jest.spyOn(ethers, "Contract") + const signer = {} as EthereumSigner const vaultAddress = EthereumAddress.from( ethers.Wallet.createRandom().address, @@ -45,6 +46,7 @@ describe("BitcoinDepositor", () => { .fn() .mockResolvedValue(testData.depositorFeeDivisor), minDepositAmount: jest.fn().mockImplementation(() => minDepositAmount), + runner: signer, } let depositor: EthereumBitcoinDepositor @@ -62,7 +64,7 @@ describe("BitcoinDepositor", () => { depositor = new EthereumBitcoinDepositor( { - signer: {} as EthereumSigner, + signer, address: depositorAddress.identifierHex, }, "sepolia", @@ -268,9 +270,9 @@ describe("BitcoinDepositor", () => { ) }) - describe("estimateDepositFees", () => { + describe("calculateDepositFee", () => { const mockedBridgeContractInstance = { - depositsParameters: jest + depositParameters: jest .fn() .mockResolvedValue(testData.depositParameters), } @@ -337,13 +339,14 @@ describe("BitcoinDepositor", () => { expect(Contract).toHaveBeenNthCalledWith( 1, `0x${bridgeAddress.identifierHex}`, - ["function depositsParameters()"], + ["function depositParameters()"], + mockedContractInstance.runner, ) }) it("should get the deposit parameters from chain", () => { expect( - mockedBridgeContractInstance.depositsParameters, + mockedBridgeContractInstance.depositParameters, ).toHaveBeenCalled() }) @@ -351,11 +354,12 @@ describe("BitcoinDepositor", () => { expect(mockedContractInstance.tbtcVault).toHaveBeenCalled() }) - it("should create the ethers Contract instance of the Bridge contract", () => { + it("should create the ethers Contract instance of the tBTC Vault contract", () => { expect(Contract).toHaveBeenNthCalledWith( 2, `0x${vaultAddress.identifierHex}`, ["function optimisticMintingFeeDivisor()"], + mockedContractInstance.runner, ) }) @@ -381,7 +385,7 @@ describe("BitcoinDepositor", () => { mockedContractInstance.bridge.mockClear() mockedContractInstance.tbtcVault.mockClear() mockedContractInstance.depositorFeeDivisor.mockClear() - mockedBridgeContractInstance.depositsParameters.mockClear() + mockedBridgeContractInstance.depositParameters.mockClear() mockedVaultContractInstance.optimisticMintingFeeDivisor.mockClear() result2 = await depositor.calculateDepositFee(amountToStake) @@ -390,7 +394,7 @@ describe("BitcoinDepositor", () => { it("should get the deposit parameters from cache", () => { expect(mockedContractInstance.bridge).toHaveBeenCalledTimes(0) expect( - mockedBridgeContractInstance.depositsParameters, + mockedBridgeContractInstance.depositParameters, ).toHaveBeenCalledTimes(0) }) From b67eea06a4a9c5d45d8d9ed0ccdf2f9393b8fe0c Mon Sep 17 00:00:00 2001 From: Rafal Czajkowski Date: Thu, 25 Apr 2024 21:18:46 +0200 Subject: [PATCH 110/110] Fix human-readable contract abi Use correct format of view functions in human-readable contract abi format. --- sdk/src/lib/ethereum/bitcoin-depositor.ts | 11 +++++++---- sdk/test/lib/ethereum/tbtc-depositor.test.ts | 6 ++++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/sdk/src/lib/ethereum/bitcoin-depositor.ts b/sdk/src/lib/ethereum/bitcoin-depositor.ts index 98e9fa14d..7e31d2913 100644 --- a/sdk/src/lib/ethereum/bitcoin-depositor.ts +++ b/sdk/src/lib/ethereum/bitcoin-depositor.ts @@ -210,23 +210,26 @@ class EthereumBitcoinDepositor const bridgeAddress = await this.instance.bridge() const bridge = new Contract( bridgeAddress, - ["function depositParameters()"], + [ + "function depositParameters() view returns (uint64 depositDustThreshold, uint64 depositTreasuryFeeDivisor, uint64 depositTxMaxFee, uint32 depositRevealAheadPeriod)", + ], this.instance.runner, ) - const depositParameters = + const { depositTreasuryFeeDivisor, depositTxMaxFee } = (await bridge.depositParameters()) as TbtcDepositParameters const vaultAddress = await this.getTbtcVaultChainIdentifier() const vault = new Contract( `0x${vaultAddress.identifierHex}`, - ["function optimisticMintingFeeDivisor()"], + ["function optimisticMintingFeeDivisor() view returns (uint32)"], this.instance.runner, ) const optimisticMintingFeeDivisor = (await vault.optimisticMintingFeeDivisor()) as bigint this.#cache.tbtcBridgeMintingParameters = { - ...depositParameters, + depositTreasuryFeeDivisor, + depositTxMaxFee, optimisticMintingFeeDivisor, } return this.#cache.tbtcBridgeMintingParameters diff --git a/sdk/test/lib/ethereum/tbtc-depositor.test.ts b/sdk/test/lib/ethereum/tbtc-depositor.test.ts index 527188b48..aff33ce6d 100644 --- a/sdk/test/lib/ethereum/tbtc-depositor.test.ts +++ b/sdk/test/lib/ethereum/tbtc-depositor.test.ts @@ -339,7 +339,9 @@ describe("BitcoinDepositor", () => { expect(Contract).toHaveBeenNthCalledWith( 1, `0x${bridgeAddress.identifierHex}`, - ["function depositParameters()"], + [ + "function depositParameters() view returns (uint64 depositDustThreshold, uint64 depositTreasuryFeeDivisor, uint64 depositTxMaxFee, uint32 depositRevealAheadPeriod)", + ], mockedContractInstance.runner, ) }) @@ -358,7 +360,7 @@ describe("BitcoinDepositor", () => { expect(Contract).toHaveBeenNthCalledWith( 2, `0x${vaultAddress.identifierHex}`, - ["function optimisticMintingFeeDivisor()"], + ["function optimisticMintingFeeDivisor() view returns (uint32)"], mockedContractInstance.runner, ) })