Threshold Network 백서

Threshold Network

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 36쪽 중 8쪽

an Ethers signer or provider as a parameter and uses it to interact with tBTC contracts deployed on Ethereum Sepolia * Needs to receive as a second parameter the value `true` to activate the crosschain mode. * Automatically configures an Electrum Bitcoin client to communicate with the Bitcoin testnet (communication is done through a set of pre-configured Electrum servers) The usage of this function is exactly the same as for the previous `TBTC.initializeMainnet` function. ```typescript import * as ethers from "ethers" import { TBTC } from "@keep-network/tbtc-v2.ts" // Create an Ethers provider. Pass the URL of an Ethereum and Arbitrum testnet node. // For example, Alchemy or Infura. const ethProvider = new ethers.providers.JsonRpcProvider("...") const arbProvider = new ethers.providers.JsonRpcProvider("...") // Create an Ethers signer. Pass the private key and the above provider. const arbSigner = new ethers.Wallet("...", provider) // If you want to initialize the SDK, it is enough to pass the provider. const sdk = await TBTC.initializeSepolia(ethProvider, true) // Initialize cross-chain functionality for TBTC on Arbitrum await sdk.initializeCrossChain("Arbitrum", arbSigner); // The SDK will be ready to launch read and write in Arbitrum. ``` # Custom mode Apart from the opinionated initialization functions, the SDK provides a flexible TBTC.initializeCustom function for advanced users. This function allows setting up the SDK to work with custom tBTC smart contracts and custom Bitcoin network. For example, it can be used to address the following use cases: #### Using locally deployed tBTC contracts and local Bitcoin network This is the common case when you are setting up a development environment. Let's suppose you have deployed the tBTC contracts on your local Ethereum chain and you are using a [local Bitcoin regtest node](https://developer.bitcoin.org/examples/testing.html#regtest-mode). The following snippet demonstrates SDK initialization in that case: ```typescript import * as ethers from "ethers" import { TBTC, TBTCContracts, EthereumBridge, EthereumTBTCToken, EthereumTBTCVault, EthereumWalletRegistry, ElectrumClient, } from "@keep-network/tbtc-v2.ts" // Create an Ethers provider. Pass the URL of your local Ethereum node. const provider = new ethers.providers.JsonRpcProvider("...") // Create an Ethers signer. Pass the private key and the above provider. const signer = new ethers.Wallet("...", provider) // Create a reference to your locally deployed tBTC contracts. // ABI will be loaded from the following contract packages: // - @keep-network/tbtc-v2 // - @keep-network/ecdsa const tbtcContracts: TBTCContracts = { bridge: new EthereumBridge({address: "...", signerOrProvider: signer}), tbtcToken: new EthereumTBTCToken({address: "...", signerOrProvider: signer}), tbtcVault: new EthereumTBTCVault({address: "...", signerOrProvider: signer}), walletRegistry: new EthereumWalletRegistry({address: "...", signerOrProvider: signer}) } // Create an Electrum Bitcoin client pointing to your local regtest node. const bitcoinClient = ElectrumClient.fromUrl("...") // Initialize the SDK. const sdk = await TBTC.initializeCustom(tbtcContracts, bitcoinClient) ``` #### Using a custom Bitcoin client instead of the automatically configured one In some cases, you may want to initialize the SDK for mainnet/testnet, but point the Electrum Bitcoin client to your own server. Here is how you can do that: ```typescript import * as ethers from "ethers" import { TBTC, TBTCContracts, loadEthereumContracts, ElectrumClient } from "@keep-network/tbtc-v2.ts" // Create an Ethers provider. Pass a URL of an Ethereum mainnet node. // For example, Alchemy or Infura. const provider = new ethers.providers.JsonRpcProvider("...") // Create an Ethers signer. Pass the private key and the above provider. const signer = new ethers.Wallet("...", provider) // Load tBTC Ethereum mainnet contracts manually. const tbtcContracts: TBTCContracts = await loadEthereumContracts(signer, "mainnet") // Create an Electrum Bitcoin client pointing to your own mainnet server. const bitcoinClient = ElectrumClient.fromUrl("...") // Initialize the SDK with Electrum Bitcoin client pointing to your own server. const sdk = await TBTC.initializeCustom(tbtcContracts, bitcoinClient) ``` You can even use another (non-Electrum) Bitcoin client implementation. This is how you can achieve that: ```typescript import * as ethers from "ethers" import { TBTC, TBTCContracts, loadEthereumContracts, BitcoinClient, } from "@keep-network/tbtc-v2.ts" // Create an Ethers provider. Pass a URL of an Ethereum mainnet node. // For example, Alchemy or Infura. const provider = new ethers.providers.JsonRpcProvider("...") // Create an Ethers signer. Pass the private key and the above provider. const signer = new ethers.Wallet("...", provider) // Load tBTC Ethereum mainnet contracts manually. const tbtcContracts: TBTCContracts = await loadEthereumContracts(signer, "mainnet") // Create your own Bitcoin client implementation. class OwnBitcoinClientImpl implements BitcoinClient { // Implement all required methods } // Initialize your own Bitcoin client implementation. const bitcoinClient = new OwnBitcoinClientImpl() // Initialize the SDK with your own Bitcoin client implementation. const sdk = await TBTC.initializeCustom(tbtcContracts, bitcoinClient) ``` #### Using mock tBTC contracts and mock Bitcoin network Sometimes, you may also want to initialize the SDK with mock tBTC contracts and Bitcoin network for testing purposes. This can be done as follows: ```typescript import { TBTC, TBTCContracts, Bridge, TBTCToken, TBTCVault, WalletRegistry, BitcoinClient, } from "@keep-network/tbtc-v2.ts" // Create mock Bridge contract implementation. class MockBridge implements Bridge { // Implement all required methods } // Create mock TBTCToken contract implementation. class MockTBTCToken implements TBTCToken { // Implement all required methods } // Create mock TBTCVault contract implementation. class MockTBTCVault implements TBTCVault { // Implement all required methods } // Create mock WalletRegistry contract implementation. class MockWalletRegistry implements WalletRegistry { // Implement all required methods } // Create mock BitcoinClient contract implementation. class MockBitcoinClient implements BitcoinClient { // Implement all required methods } // Create instances of the mock contracts. const tbtcContracts: TBTCContracts = { bridge: new MockBridge(), tbtcToken: new MockTBTCToken(), tbtcVault: new MockTBTCVault(), walletRegistry: new MockWalletRegistry() } // Create an instance of the mock Bitcoin client. const bitcoinClient = new MockBitcoinClient() // Initialize the SDK. const sdk = await TBTC.initializeCustom(tbtcContracts, bitcoinClient) ``` # Deposit and mint The main feature of the tBTC bridge is depositing BTC and using it to mint the ERC-20 TBTC token. This guide explains how to perform this process using the SDK.  ### Initialize the SDK First, initialize the SDK, as described in the [Initialize SDK](/app-development/tbtc-sdk/guides/initialize-sdk) guide. ### Initiate the deposit  Once the SDK is initialized, you can initiate the deposit and get their Bitcoin address in the following way: ```typescript import { TBTC } from "@keep-network/tbtc-v2.ts" // Initialized SDK. const sdk: TBTC // Set the P2WPKH/P2PKH Bitcoin recovery address. It can be used to recover // deposited BTC in case something exceptional happens. const bitcoinRecoveryAddress: string = "..." // Initiate the deposit. const deposit = await sdk.deposits.initiateDeposit(bitcoinRecoveryAddress) // Take the Bitcoin deposit address. BTC must be sent here. const bitcoinDepositAddress = await deposit.getBitcoinAddress() ``` ### Make the Bitcoin deposit transaction The next step is doing the actual Bitcoin deposit transaction to the deposit address. There are two possible ways to do so: * **Recommended**: Use an external Bitcoin wallet  * **Non-recommended**: Use the experimental SDK [`DepositFunding`](https://github.com/keep-network/tbtc-v2/blob/f78fe3808733a56cdd5c9e4adcaaf84921cadd3b/typescript/src/services/deposits/funding.ts#L27) component. This code is used for testing purposes and **is not safe** for production use! ### Initiate minting Once the Bitcoin deposit transaction is done, minting can be initiated. This can be done using the `initiateMinting` method exposed by the `Deposit` class. This method has two modes: * **Automatic**: Automatically detect the latest funding UTXO and use it to initiate minting. This mode is the default one that should be used when a single Bitcoin deposit transaction has been made. * **Manual**: Take a funding UTXO as a parameter and use it to initiate minting. This mode can be useful when multiple Bitcoin deposit transactions target the same deposit address. Here is an example of both: {% tabs %} {% tab title="Automatic" %} ```typescript // Initiate minting using latest funding UTXO. Returns hash of the // initiate minting transaction. Can throw an error if there are no // Bitcoin funding transactions targeting this deposit address. // In that case, consider retrying after a delay. const txHash = await deposit.initiateMinting() ``` {% endtab %} {% tab title="Manual" %} ```typescript // Detect funding UTXOs manually. There can be more than one. await fundingUTXOs = await deposit.detectFunding() // Initiate minting using one of the funding UTXOs. Returns hash of the // initiate minting transaction. const txHash = await deposit.initiateMinting(fundingUTXOs[0]) ``` {% endtab %} {% endtabs %} # Unmint and redeem Another core feature of the tBTC bridge is unminting (burning) TBTC tokens and redeeming BTC in return. This guide explains how to perform this process using the SDK.  ### Initialize the SDK First, initialize the SDK, as described in the [Initialize SDK](/app-development/tbtc-sdk/guides/initialize-sdk) guide. ### Request redemption Once the SDK is initialized, you can unmint and request for redemption in the following way: ```typescript import { TBTC } from "@keep-network/tbtc-v2.ts" import { BigNumber } from "ethers" // Initialized SDK. const sdk: TBTC // Set the P2WPKH/P2PKH or P2WSH/P2SH Bitcoin redeemer address. This is the // address where redeemed BTC will land. const bitcoinRedeemerAddress: string = "..." // Set the desired redemption amount using 1e18 precision. No need to do an // explicit approval on the TBTC token upfront. const amount = BigNumber.from(5 * 1e18) // Request redemption. This action will burn TBTC tokens and register a // redemption request in the bridge. Returns the hash of the request redemption // transaction and the target wallet public key that will handle the redemption. const { targetChainTxHash, walletPublicKey } = await sdk.redemptions.requestRedemption(bitcoinRedeemerAddress, amount) ``` # tBTC Contracts API # Bridge API You can learn about APIs of contracts related to the Bridge under the following links: [Bank](/app-development/tbtc-contracts-api/tbtc-v2-api/bank) [BitcoinTx](/app-development/tbtc-contracts-api/tbtc-v2-api/bitcointx) [Bridge](/app-development/tbtc-contracts-api/tbtc-v2-api/bridge) [BridgeGovernance](/app-development/tbtc-contracts-api/tbtc-v2-api/bridgegovernance) [BridgeGovernanceParameters](/app-development/tbtc-contracts-api/tbtc-v2-api/bridgegovernanceparameters) [BridgeState](/app-development/tbtc-contracts-api/tbtc-v2-api/bridgestate) [Deposit](/app-development/tbtc-contracts-api/tbtc-v2-api/deposit) [DepositSweep](/app-development/tbtc-contracts-api/tbtc-v2-api/depositsweep) [DonationVault](/app-development/tbtc-contracts-api/tbtc-v2-api/donationvault) [EcdsaLib](/app-development/tbtc-contracts-api/tbtc-v2-api/ecdsalib) [Fraud](/app-development/tbtc-contracts-api/tbtc-v2-api/fraud) [GovernanceUtils](/app-development/tbtc-contracts-api/tbtc-v2-api/governanceutils) [Heartbeat](/app-development/tbtc-contracts-api/tbtc-v2-api/heartbeat) [IReceiveBalanceApproval](/app-development/tbtc-contracts-api/tbtc-v2-api/ireceivebalanceapproval) [IRelay](/app-development/tbtc-contracts-api/tbtc-v2-api/irelay) [IVault](/app-development/tbtc-contracts-api/tbtc-v2-api/ivault) [L2tBTC](/app-development/tbtc-contracts-api/tbtc-v2-api/l2tbtc) [L2WormholeGateway](/app-development/tbtc-contracts-api/tbtc-v2-api/l2wormholegateway) [LightRelay](/app-development/tbtc-contracts-api/tbtc-v2-api/lightrelay) [LightRelayMaintainerProxy](/app-development/tbtc-contracts-api/tbtc-v2-api/lightrelaymaintainerproxy) [MaintainerProxy](/app-development/tbtc-contracts-api/tbtc-v2-api/maintainerproxy) [MovingFunds](/app-development/tbtc-contracts-api/tbtc-v2-api/movingfunds) [Redemption](/app-development/tbtc-contracts-api/tbtc-v2-api/redemption) [tBTC](/app-development/tbtc-contracts-api/tbtc-v2-api/tbtc) [tBTCOptimisticMinting](/app-development/tbtc-contracts-api/tbtc-v2-api/tbtcoptimisticminting) [tBTCVault](/app-development/tbtc-contracts-api/tbtc-v2-api/tbtcvault) [VendingMachine](/app-development/tbtc-contracts-api/tbtc-v2-api/vendingmachine) [VendingMachineV2](/app-development/tbtc-contracts-api/tbtc-v2-api/vendingmachinev2) [VendingMachineV3](/app-development/tbtc-contracts-api/tbtc-v2-api/vendingmachinev3) [WalletCoordinator](/app-development/tbtc-contracts-api/tbtc-v2-api/walletcoordinator) [Wallets](/app-development/tbtc-contracts-api/tbtc-v2-api/wallets) # Bank ## Bank Bank is a central component tracking Bitcoin balances. Balances can be transferred between balance owners, and balance owners can approve their balances to be spent by others. Balances in the Bank are updated for depositors who deposited their Bitcoin into the Bridge and only the Bridge can increase balances. Bank is a governable contract and the Governance can upgrade the Bridge address. ### bridge ```solidity address bridge ``` ### balanceOf ```solidity mapping(address => uint256) balanceOf ``` The balance of the given account in the Bank. Zero by default. ### allowance ```solidity mapping(address => mapping(address => uint256)) allowance ``` The remaining amount of balance a spender will be allowed to transfer on behalf of an owner using `transferBalanceFrom`. Zero by default. ### nonces ```solidity mapping(address => uint256) nonces ``` Returns the current nonce for an EIP2612 permission for the provided balance owner to protect against replay attacks. Used to construct an EIP2612 signature provided to the `permit` function. ### cachedChainId ```solidity uint256 cachedChainId ``` ### cachedDomainSeparator ```solidity bytes32 cachedDomainSeparator ``` ### PERMIT\_TYPEHASH ```solidity bytes32 PERMIT_TYPEHASH ``` Returns an EIP2612 Permit message hash. Used to construct an EIP2612 signature provided to the `permit` function. ### BalanceTransferred ```solidity event BalanceTransferred(address from, address to, uint256 amount) ``` ### BalanceApproved ```solidity event BalanceApproved(address owner, address spender, uint256 amount) ``` ### BalanceIncreased ```solidity event BalanceIncreased(address owner, uint256 amount) ``` ### BalanceDecreased ```solidity event BalanceDecreased(address owner, uint256 amount) ``` ### BridgeUpdated ```solidity event BridgeUpdated(address newBridge) ``` ### onlyBridge ```solidity modifier onlyBridge() ``` ### constructor ```solidity constructor() public ``` ### updateBridge ```solidity function updateBridge(address _bridge) external ``` Allows the Governance to upgrade the Bridge address. The function does not implement any governance delay and does not check the status of the Bridge. The Governance implementation needs to ensure all requirements for the upgrade are satisfied before executing this function. Requirements: * The new Bridge address must not be zero. #### Parameters | Name | Type | Description | | -------- | ------- | ----------------------- | | \_bridge | address | The new Bridge address. | ### transferBalance ```solidity function transferBalance(address recipient, uint256 amount) external ``` Moves the given `amount` of balance from the caller to `recipient`. Requirements: * `recipient` cannot be the zero address, * the caller must have a balance of at least `amount`. #### Parameters | Name | Type | Description | | --------- | ------- | -------------------------------------- | | recipient | address | The recipient of the balance. | | amount | uint256 | The amount of the balance transferred. | ### approveBalance ```solidity function approveBalance(address spender, uint256 amount) external ``` Sets `amount` as the allowance of `spender` over the caller's balance. Does not allow updating an existing allowance to a value that is non-zero to avoid someone using both the old and the new allowance by unfortunate transaction ordering. To update an allowance to a non-zero value please set it to zero first or use `increaseBalanceAllowance` or `decreaseBalanceAllowance` for an atomic update. If the `amount` is set to `type(uint256).max`, `transferBalanceFrom` will not reduce an allowance. #### Parameters | Name | Type | Description | | ------- | ------- | ------------------------------------------------------ | | spender | address | The address that will be allowed to spend the balance. | | amount | uint256 | The amount the spender is allowed to spend. | ### approveBalanceAndCall ```solidity function approveBalanceAndCall(address spender, uint256 amount, bytes extraData) external ``` Sets the `amount` as an allowance of a smart contract `spender` over the caller's balance and calls the `spender` via `receiveBalanceApproval`. If the `amount` is set to `type(uint256).max`, the potential `transferBalanceFrom` executed in `receiveBalanceApproval` of `spender` will not reduce an allowance. Beware that changing an allowance with this function brings the risk that `spender` may use both the old and the new allowance by unfortunate transaction ordering. Please use `increaseBalanceAllowance` and `decreaseBalanceAllowance` to eliminate the risk. #### Parameters | Name | Type | Description | | --------- | ------- | ------------------------------------------------------------------------------ | | spender | address | The smart contract that will be allowed to spend the balance. | | amount | uint256 | The amount the spender contract is allowed to spend. | | extraData | bytes | Extra data passed to the `spender` contract via `receiveBalanceApproval` call. | ### increaseBalanceAllowance ```solidity function increaseBalanceAllowance(address spender, uint256 addedValue) external ``` Atomically increases the caller's balance allowance granted to `spender` by the given `addedValue`. #### Parameters | Name | Type | Description | | ---------- | ------- | --------------------------------------------------------- | | spender | address | The spender address for which the allowance is increased. | | addedValue | uint256 | The amount by which the allowance is increased. | ### decreaseBalanceAllowance ```solidity function decreaseBalanceAllowance(address spender, uint256 subtractedValue) external ``` Atomically decreases the caller's balance allowance granted to `spender` by the given `subtractedValue`. Requirements: * `spender` must not be the zero address, * the current allowance for `spender` must not be lower than the `subtractedValue`. #### Parameters | Name | Type | Description | | --------------- | ------- | --------------------------------------------------------- | | spender | address | The spender address for which the allowance is decreased. | | subtractedValue | uint256 | The amount by which the allowance is decreased. | ### transferBalanceFrom ```solidity function transferBalanceFrom(address spender, address recipient, uint256 amount) external ``` Moves `amount` of balance from `spender` to `recipient` using the allowance mechanism. `amount` is then ded
프로젝트로 돌아가기