Skip to content

Latest commit

 

History

History

api-reference

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

@keep-network/tbtc-v2.ts

Table of contents

Namespaces

Enumerations

Classes

Interfaces

Type Aliases

Variables

Functions

Type Aliases

BitcoinTxInput

Ƭ BitcoinTxInput: BitcoinTxOutpoint & { scriptSig: Hex }

Data about a Bitcoin transaction input.

Defined in

src/lib/bitcoin/tx.ts:63


BitcoinUtxo

Ƭ BitcoinUtxo: BitcoinTxOutpoint & { value: BigNumber }

Data about a Bitcoin unspent transaction output.

Defined in

src/lib/bitcoin/tx.ts:93


ChainMapping

Ƭ ChainMapping: Object

Type representing a mapping between specific L1 and L2 chains.

Type declaration

Name Type Description
base? Base Identifier of the Base L2 chain.
ethereum? Ethereum Identifier of the Ethereum L1 chain.

Defined in

src/lib/contracts/chain.ts:26


CrossChainContracts

Ƭ CrossChainContracts: L2CrossChainContracts & L1CrossChainContracts

Convenience type aggregating TBTC cross-chain contracts forming a connector between TBTC L1 ledger chain and a specific supported L2/side-chain.

Defined in

src/lib/contracts/cross-chain.ts:12


CrossChainDepositorMode

Ƭ CrossChainDepositorMode: "L2Transaction" | "L1Transaction"

Mode of operation for the cross-chain depositor proxy:

  • [L2Transaction]: The proxy will reveal the deposit using a transaction on the L2 chain. The tBTC system is responsible for relaying the deposit to the tBTC L1 chain.
  • [L1Transaction]: The proxy will directly reveal the deposit using a transaction on the tBTC L1 chain.

Defined in

src/services/deposits/cross-chain.ts:19


DepositRevealedEvent

Ƭ DepositRevealedEvent: DepositReceipt & Pick<DepositRequest, "amount" | "vault"> & { fundingOutputIndex: number ; fundingTxHash: BitcoinTxHash } & ChainEvent

Represents an event emitted on deposit reveal to the on-chain bridge.

Defined in

src/lib/contracts/bridge.ts:293


DkgResultApprovedEvent

Ƭ DkgResultApprovedEvent: { approver: ChainIdentifier ; resultHash: Hex } & ChainEvent

Represents an event emitted when a DKG result is approved on the on-chain wallet registry.

Defined in

src/lib/contracts/wallet-registry.ts:64


DkgResultChallengedEvent

Ƭ DkgResultChallengedEvent: { challenger: ChainIdentifier ; reason: string ; resultHash: Hex } & ChainEvent

Represents an event emitted when a DKG result is challenged on the on-chain wallet registry.

Defined in

src/lib/contracts/wallet-registry.ts:79


DkgResultSubmittedEvent

Ƭ DkgResultSubmittedEvent: { result: DkgResult ; resultHash: Hex ; seed: Hex } & ChainEvent

Represents an event emitted when a DKG result is submitted to the on-chain wallet registry.

Defined in

src/lib/contracts/wallet-registry.ts:45


ElectrumClientOptions

Ƭ ElectrumClientOptions: object

Additional options used by the Electrum server.

Defined in

src/lib/electrum/client.ts:49


ErrorMatcherFn

Ƭ ErrorMatcherFn: (err: unknown) => boolean

Type declaration

▸ (err): boolean

Parameters
Name Type
err unknown
Returns

boolean

True if the error matches, false otherwise.

Defined in

src/lib/utils/backoff.ts:42


EthereumSigner

Ƭ EthereumSigner: Signer | providers.Provider

Represents an Ethereum signer. This type is a wrapper for Ethers-specific types and can be either a Signer that can make write transactions or a Provider that works only in the read-only mode.

Defined in

src/lib/ethereum/index.ts:34


ExecutionLoggerFn

Ƭ ExecutionLoggerFn: (msg: string) => void

Type declaration

▸ (msg): void

A function that is called with execution status messages.

Parameters
Name Type
msg string
Returns

void

Defined in

src/lib/utils/backoff.ts:56


L1CrossChainContracts

Ƭ L1CrossChainContracts: Object

Aggregates L1-specific TBTC cross-chain contracts.

Type declaration

Name Type
l1BitcoinDepositor L1BitcoinDepositor

Defined in

src/lib/contracts/cross-chain.ts:25


L2Chain

Ƭ L2Chain: Exclude<keyof typeof Chains, "Ethereum">

Layer 2 chains supported by tBTC v2 contracts.

Defined in

src/lib/contracts/chain.ts:21


L2CrossChainContracts

Ƭ L2CrossChainContracts: Object

Aggregates L2-specific TBTC cross-chain contracts.

Type declaration

Name Type
l2BitcoinDepositor L2BitcoinDepositor
l2TbtcToken L2TBTCToken

Defined in

src/lib/contracts/cross-chain.ts:17


NewWalletRegisteredEvent

Ƭ NewWalletRegisteredEvent: { ecdsaWalletID: Hex ; walletPublicKeyHash: Hex } & ChainEvent

Represents an event emitted when new wallet is registered on the on-chain bridge.

Defined in

src/lib/contracts/bridge.ts:457


OptimisticMintingCancelledEvent

Ƭ OptimisticMintingCancelledEvent: { depositKey: Hex ; guardian: ChainIdentifier } & ChainEvent

Represents an event that is emitted when an optimistic minting request is cancelled on chain.

Defined in

src/lib/contracts/tbtc-vault.ts:170


OptimisticMintingFinalizedEvent

Ƭ OptimisticMintingFinalizedEvent: { depositKey: Hex ; depositor: ChainIdentifier ; minter: ChainIdentifier ; optimisticMintingDebt: BigNumber } & ChainEvent

Represents an event that is emitted when an optimistic minting request is finalized on chain.

Defined in

src/lib/contracts/tbtc-vault.ts:186


OptimisticMintingRequest

Ƭ OptimisticMintingRequest: Object

Represents optimistic minting request for the given deposit revealed to the Bridge.

Type declaration

Name Type Description
finalizedAt number UNIX timestamp at which the optimistic minting was finalized. 0 if not yet finalized.
requestedAt number UNIX timestamp at which the optimistic minting was requested.

Defined in

src/lib/contracts/tbtc-vault.ts:120


OptimisticMintingRequestedEvent

Ƭ OptimisticMintingRequestedEvent: { amount: BigNumber ; depositKey: Hex ; depositor: ChainIdentifier ; fundingOutputIndex: number ; fundingTxHash: BitcoinTxHash ; minter: ChainIdentifier } & ChainEvent

Represents an event that is emitted when a new optimistic minting is requested on chain.

Defined in

src/lib/contracts/tbtc-vault.ts:136


RedemptionRequestedEvent

Ƭ RedemptionRequestedEvent: Omit<RedemptionRequest, "requestedAt"> & { walletPublicKeyHash: Hex } & ChainEvent

Represents an event emitted on redemption request.

Defined in

src/lib/contracts/bridge.ts:344


RetrierFn

Ƭ RetrierFn<T>: (fn: () => Promise<T>) => Promise<T>

Type parameters

Name
T

Type declaration

▸ (fn): Promise<T>

Parameters
Name Type Description
fn () => Promise<T> The function to be retried.
Returns

Promise<T>

Defined in

src/lib/utils/backoff.ts:51


TBTCContracts

Ƭ TBTCContracts: Object

Convenience type aggregating all TBTC core contracts.

Type declaration

Name Type
bridge Bridge
tbtcToken TBTCToken
tbtcVault TBTCVault
walletRegistry WalletRegistry

Defined in

src/lib/contracts/index.ts:19

Variables

BitcoinAddressConverter

Const BitcoinAddressConverter: Object

Utility functions allowing to perform Bitcoin address conversions.

Type declaration

Name Type
addressToOutputScript (address: string, bitcoinNetwork: BitcoinNetwork) => Hex
addressToPublicKeyHash (address: string, bitcoinNetwork: BitcoinNetwork) => Hex
outputScriptToAddress (script: Hex, bitcoinNetwork: BitcoinNetwork) => string
publicKeyHashToAddress (publicKeyHash: Hex, witness: boolean, bitcoinNetwork: BitcoinNetwork) => string
publicKeyToAddress (publicKey: Hex, bitcoinNetwork: BitcoinNetwork, witness: boolean) => string

Defined in

src/lib/bitcoin/address.ts:112


BitcoinCompactSizeUint

Const BitcoinCompactSizeUint: Object

Utility functions allowing to deal with Bitcoin compact size uints.

Type declaration

Name Type
read (varLenData: Hex) => { byteLength: number ; value: number }

Defined in

src/lib/bitcoin/csuint.ts:50


BitcoinHashUtils

Const BitcoinHashUtils: Object

Utility functions allowing to deal with Bitcoin hashes.

Type declaration

Name Type
computeHash160 (text: Hex) => Hex
computeHash256 (text: Hex) => Hex
computeSha256 (text: Hex) => Hex
hashLEToBigNumber (hash: Hex) => BigNumber

Defined in

src/lib/bitcoin/hash.ts:52


BitcoinHeaderSerializer

Const BitcoinHeaderSerializer: Object

Utility functions allowing to serialize and deserialize Bitcoin block headers.

Type declaration

Name Type
deserializeHeader (rawHeader: Hex) => BitcoinHeader
deserializeHeadersChain (rawHeadersChain: Hex) => BitcoinHeader[]
serializeHeader (header: BitcoinHeader) => Hex

Defined in

src/lib/bitcoin/header.ts:109


BitcoinLocktimeUtils

Const BitcoinLocktimeUtils: Object

Utility functions allowing to deal with Bitcoin locktime.

Type declaration

Name Type
calculateLocktime (locktimeStartedAt: number, locktimeDuration: number) => Hex
locktimeToNumber (locktimeLE: string | Buffer) => number

Defined in

src/lib/bitcoin/tx.ts:234


BitcoinPrivateKeyUtils

Const BitcoinPrivateKeyUtils: Object

Utility functions allowing to perform operations on Bitcoin ECDSA private keys.

Type declaration

Name Type
createKeyPair (privateKey: string, bitcoinNetwork: BitcoinNetwork) => ECPairInterface

Defined in

src/lib/bitcoin/ecdsa-key.ts:77


BitcoinPublicKeyUtils

Const BitcoinPublicKeyUtils: Object

Utility functions allowing to perform operations on Bitcoin ECDSA public keys.

Type declaration

Name Type
compressPublicKey (publicKey: Hex) => string
isCompressedPublicKey (publicKey: Hex) => boolean

Defined in

src/lib/bitcoin/ecdsa-key.ts:51


BitcoinScriptUtils

Const BitcoinScriptUtils: Object

Utility functions allowing to deal with Bitcoin scripts.

Type declaration

Name Type
isP2PKHScript (script: Hex) => boolean
isP2SHScript (script: Hex) => boolean
isP2WPKHScript (script: Hex) => boolean
isP2WSHScript (script: Hex) => boolean

Defined in

src/lib/bitcoin/script.ts:63


BitcoinTargetConverter

Const BitcoinTargetConverter: Object

Utility functions allowing to perform Bitcoin target conversions.

Type declaration

Name Type
bitsToTarget (bits: number) => BigNumber
targetToDifficulty (target: BigNumber) => BigNumber

Defined in

src/lib/bitcoin/header.ts:268


ChainMappings

Const ChainMappings: ChainMapping[]

List of chain mappings supported by tBTC v2 contracts.

Defined in

src/lib/contracts/chain.ts:40

Functions

assembleBitcoinSpvProof

assembleBitcoinSpvProof(transactionHash, requiredConfirmations, bitcoinClient): Promise<BitcoinTx & BitcoinSpvProof>

Assembles a proof that a given transaction was included in the blockchain and has accumulated the required number of confirmations.

Parameters

Name Type Description
transactionHash BitcoinTxHash Hash of the transaction being proven.
requiredConfirmations number Required number of confirmations.
bitcoinClient BitcoinClient Bitcoin client used to interact with the network.

Returns

Promise<BitcoinTx & BitcoinSpvProof>

Bitcoin transaction along with the inclusion proof.

Defined in

src/lib/bitcoin/spv.ts:75


backoffRetrier

backoffRetrier<T>(retries, backoffStepMs?, logger?, errorMatcher?): RetrierFn<T>

Returns a retrier that can be passed a function to be retried retries number of times, with exponential backoff. The result will return the function's return value if no exceptions are thrown. It will only retry if the function throws an exception matched by matcher; {@see retryAll} can be used to retry no matter the exception, though this is not necessarily recommended in production.

Example usage:

 await url.get("https://example.com/") // may transiently fail
 // Retries 3 times with exponential backoff, no matter what error is
 // reported by `url.get`.
 backoffRetrier(3)(async () => url.get("https://example.com"))
 // Retries 3 times with exponential backoff, but only if the error
 // message includes "server unavailable".
 backoffRetrier(3, (_) => _.message.includes('server unavailable'))(
   async () => url.get("https://example.com"))
 )

Type parameters

Name
T

Parameters

Name Type Default value Description
retries number undefined The number of retries to perform before bubbling the failure out.
backoffStepMs number 1000 Initial backoff step in milliseconds that will be increased exponentially for subsequent retry attempts. (default = 1000 ms)
logger ExecutionLoggerFn console.debug A logger function to pass execution messages.
errorMatcher? ErrorMatcherFn retryAll A matcher function that receives the error when an exception is thrown, and returns true if the error should lead to a retry. A false return will rethrow the error and terminate the retry loop.

Returns

RetrierFn<T>

A function that can retry any function.

Defined in

src/lib/utils/backoff.ts:89


chainIdFromSigner

chainIdFromSigner(signer): Promise<string>

Resolves the chain ID from the given signer.

Parameters

Name Type Description
signer EthereumSigner The signer whose chain ID should be resolved.

Returns

Promise<string>

Chain ID as a string.

Defined in

src/lib/ethereum/index.ts:41


computeElectrumScriptHash

computeElectrumScriptHash(script): string

Converts a Bitcoin script to an Electrum script hash. See [Electrum protocol]https://electrumx.readthedocs.io/en/stable/protocol-basics.html#script-hashes

Parameters

Name Type Description
script Hex Bitcoin script as hex string

Returns

string

Electrum script hash as a hex string.

Defined in

src/lib/electrum/client.ts:668


ethereumAddressFromSigner

ethereumAddressFromSigner(signer): Promise<EthereumAddress | undefined>

Resolves the Ethereum address tied to the given signer. The address cannot be resolved for signers that works in the read-only mode

Parameters

Name Type Description
signer EthereumSigner The signer whose address should be resolved.

Returns

Promise<EthereumAddress | undefined>

Ethereum address or undefined for read-only signers.

Throws

Throws an error if the address of the signer is not a proper Ethereum address.

Defined in

src/lib/ethereum/index.ts:63


ethereumCrossChainContractsLoader

ethereumCrossChainContractsLoader(signer, chainId): Promise<CrossChainContractsLoader>

Creates the Ethereum implementation of tBTC cross-chain contracts loader. The provided signer is attached to loaded L1 contracts. The given Ethereum chain ID is used to load the L1 contracts and resolve the chain mapping that provides corresponding L2 chains IDs.

Parameters

Name Type Description
signer EthereumSigner Ethereum L1 signer.
chainId Ethereum Ethereum L1 chain ID.

Returns

Promise<CrossChainContractsLoader>

Loader for tBTC cross-chain contracts.

Throws

Throws an error if the signer's Ethereum chain ID is other than the one used to construct the loader.

Defined in

src/lib/ethereum/index.ts:118


extractBitcoinRawTxVectors

extractBitcoinRawTxVectors(rawTransaction): BitcoinRawTxVectors

Decomposes a transaction in the raw representation into version, vector of inputs, vector of outputs and locktime.

Parameters

Name Type Description
rawTransaction BitcoinRawTx Transaction in the raw format.

Returns

BitcoinRawTxVectors

Transaction data with fields represented as un-prefixed hex strings.

Defined in

src/lib/bitcoin/tx.ts:133


loadBaseCrossChainContracts

loadBaseCrossChainContracts(signer, chainId): Promise<L2CrossChainContracts>

Loads Base implementation of tBTC cross-chain contracts for the given Base chain ID and attaches the given signer there.

Parameters

Name Type Description
signer EthereumSigner Signer that should be attached to the contracts.
chainId Base Base chain ID.

Returns

Promise<L2CrossChainContracts>

Handle to the contracts.

Throws

Throws an error if the signer's Base chain ID is other than the one used to load contracts.

Defined in

src/lib/base/index.ts:22


loadEthereumCoreContracts

loadEthereumCoreContracts(signer, chainId): Promise<TBTCContracts>

Loads Ethereum implementation of tBTC core contracts for the given Ethereum chain ID and attaches the given signer there.

Parameters

Name Type Description
signer EthereumSigner Signer that should be attached to tBTC contracts.
chainId Ethereum Ethereum chain ID.

Returns

Promise<TBTCContracts>

Handle to tBTC core contracts.

Throws

Throws an error if the signer's Ethereum chain ID is other than the one used to load tBTC contracts.

Defined in

src/lib/ethereum/index.ts:82


packRevealDepositParameters

packRevealDepositParameters(depositTx, depositOutputIndex, deposit, vault?): Object

Packs deposit parameters to match the ABI of the revealDeposit and revealDepositWithExtraData functions of the Ethereum Bridge contract.

Parameters

Name Type Description
depositTx BitcoinRawTxVectors Deposit transaction data
depositOutputIndex number Index of the deposit transaction output that funds the revealed deposit
deposit DepositReceipt Data of the revealed deposit
vault? ChainIdentifier Optional parameter denoting the vault the given deposit should be routed to

Returns

Object

Packed parameters.

Name Type
extraData undefined | string
fundingTx { inputVector: string ; locktime: string ; outputVector: string ; version: string }
fundingTx.inputVector string
fundingTx.locktime string
fundingTx.outputVector string
fundingTx.version string
reveal { blindingFactor: string ; fundingOutputIndex: number = depositOutputIndex; refundLocktime: string ; refundPubKeyHash: string ; vault: string ; walletPubKeyHash: string }
reveal.blindingFactor string
reveal.fundingOutputIndex number
reveal.refundLocktime string
reveal.refundPubKeyHash string
reveal.vault string
reveal.walletPubKeyHash string

Defined in

src/lib/ethereum/bridge.ts:699


retryAll

retryAll(error): true

A convenience matcher for withBackoffRetries that retries irrespective of the error.

Parameters

Name Type Description
error any The error to match against. Not necessarily an Error instance, since the retriable function may throw a non-Error.

Returns

true

Always returns true.

Defined in

src/lib/utils/backoff.ts:9


skipRetryWhenMatched

skipRetryWhenMatched(matchers): ErrorMatcherFn

A matcher to specify list of error messages that should abort the retry loop and throw immediately.

Parameters

Name Type Description
matchers (string | RegExp)[] List of patterns for error matching.

Returns

ErrorMatcherFn

Matcher function that returns false if error matches one of the patterns. True is returned if no matches are found and retry loop should continue

Defined in

src/lib/utils/backoff.ts:20


toBitcoinJsLibNetwork

toBitcoinJsLibNetwork(bitcoinNetwork): networks.Network

Converts the provided BitcoinNetwork enumeration to a format expected by the bitcoinjs-lib library.

Parameters

Name Type Description
bitcoinNetwork BitcoinNetwork Specified Bitcoin network.

Returns

networks.Network

Network representation compatible with the bitcoinjs-lib library.

Throws

An error if the network is not supported by bitcoinjs-lib.

Defined in

src/lib/bitcoin/network.ts:55


validateBitcoinHeadersChain

validateBitcoinHeadersChain(headers, previousEpochDifficulty, currentEpochDifficulty): void

Validates a chain of consecutive block headers by checking each header's difficulty, hash, and continuity with the previous header. This function can be used to validate a series of Bitcoin block headers for their validity.

Parameters

Name Type Description
headers BitcoinHeader[] An array of block headers that form the chain to be validated.
previousEpochDifficulty BigNumber The difficulty of the previous Bitcoin epoch.
currentEpochDifficulty BigNumber The difficulty of the current Bitcoin epoch.

Returns

void

An empty return value.

Dev

The block headers must come from Bitcoin epochs with difficulties marked by the previous and current difficulties. If a Bitcoin difficulty relay is used to provide these values and the relay is up-to-date, only the recent block headers will pass validation. Block headers older than the current and previous Bitcoin epochs will fail.

Throws

If any of the block headers are invalid, or if the block header chain is not continuous.

Defined in

src/lib/bitcoin/header.ts:132


validateBitcoinSpvProof

validateBitcoinSpvProof(transactionHash, requiredConfirmations, previousDifficulty, currentDifficulty, bitcoinClient): Promise<void>

Proves that a transaction with the given hash is included in the Bitcoin blockchain by validating the transaction's inclusion in the Merkle tree and verifying that the block containing the transaction has enough confirmations.

Parameters

Name Type Description
transactionHash BitcoinTxHash The hash of the transaction to be validated.
requiredConfirmations number The number of confirmations required for the transaction to be considered valid. The transaction has 1 confirmation when it is in the block at the current blockchain tip. Every subsequent block added to the blockchain is one additional confirmation.
previousDifficulty BigNumber The difficulty of the previous Bitcoin epoch.
currentDifficulty BigNumber The difficulty of the current Bitcoin epoch.
bitcoinClient BitcoinClient The client for interacting with the Bitcoin blockchain.

Returns

Promise<void>

An empty return value.

Throws

If the transaction is not included in the Bitcoin blockchain or if the block containing the transaction does not have enough confirmations.

Dev

The function should be used within a try-catch block.

Defined in

src/lib/bitcoin/spv.ts:180


validateDepositReceipt

validateDepositReceipt(receipt): void

Validates the given deposit receipt. Throws in case of a validation error.

Parameters

Name Type Description
receipt DepositReceipt The validated deposit receipt.

Returns

void

Dev

This function does not validate the depositor's identifier as its validity is chain-specific. This parameter must be validated outside.

Defined in

src/lib/contracts/bridge.ts:233