Skip to content

Commit

Permalink
Integrate minting flow with the SDK (wip)
Browse files Browse the repository at this point in the history
  • Loading branch information
kpyszkowski committed Nov 8, 2023
1 parent 3944e7f commit d51cbfc
Show file tree
Hide file tree
Showing 7 changed files with 123 additions and 53 deletions.
1 change: 1 addition & 0 deletions src/enums/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const envVariables = [
"FEATURE_FLAG_SENTRY",
"SENTRY_DSN",
"WALLET_CONNECT_PROJECT_ID",
"USE_GOERLI_DEVELOPMENT_CONTRACTS",
] as const

export type EnvVariableKey = typeof envVariables[number]
Expand Down
8 changes: 3 additions & 5 deletions src/hooks/tbtc/useFindRedemptionInBitcoinTx.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { useCallback } from "react"
import { BitcoinAddressConverter } from "tbtc-sdk-v2"
import { useThreshold } from "../../contexts/ThresholdContext"
import {
createAddressFromOutputScript,
prependScriptPubKeyByLength,
} from "../../threshold-ts/utils"
import { prependScriptPubKeyByLength } from "../../threshold-ts/utils"
import { useGetBlock } from "../../web3/hooks"

export const useFindRedemptionInBitcoinTx = () => {
Expand Down Expand Up @@ -32,7 +30,7 @@ export const useFindRedemptionInBitcoinTx = () => {
)

return {
btcAddress: createAddressFromOutputScript(
btcAddress: BitcoinAddressConverter.outputScriptToAddress(
scriptPubKey,
threshold.tbtc.bitcoinNetwork
),
Expand Down
4 changes: 2 additions & 2 deletions src/store/tbtc/effects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
key,
removeDataForAccount,
} from "../../utils/tbtcLocalStorageData"
import { TransactionHash } from "@keep-network/tbtc-v2.ts/dist/src/bitcoin"
import { Hex } from "tbtc-sdk-v2"

export const fetchBridgeactivityEffect = async (
action: ReturnType<typeof tbtcSlice.actions.requestBridgeActivity>,
Expand Down Expand Up @@ -180,7 +180,7 @@ export const fetchUtxoConfirmationsEffect = async (
if (txConfirmations && txConfirmations >= minimumNumberOfConfirmationsNeeded)
return

const txHash = TransactionHash.from(utxo.transactionHash)
const txHash = Hex.from(utxo.transactionHash)

// Cancel any in-progress instances of this listener.
listenerApi.cancelActiveListeners()
Expand Down
1 change: 0 additions & 1 deletion src/tbtc/mock-bitcoin-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,6 @@ export class MockBitcoinClient implements BitcoinClient {
async getRawTransaction(
transactionHash: BitcoinTxHash
): Promise<BitcoinRawTx> {
console.log(this._rawTransactions)
return this._rawTransactions.get(transactionHash.toString()) as BitcoinRawTx
}

Expand Down
120 changes: 77 additions & 43 deletions src/threshold-ts/tbtc/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
// TODO: Remove ununsed imports
import {
calculateDepositAddress,
calculateDepositRefundLocktime,
DepositScriptParameters,
revealDeposit as tBTCRevealDeposit,
getRevealedDeposit as tBTCgetRevealedDeposit,
RevealedDeposit,
} from "@keep-network/tbtc-v2.ts/dist/src/deposit"
//@ts-ignore
import * as CryptoJS from "crypto-js"
import {
getContract,
getProviderOrSigner,
Expand All @@ -21,6 +16,7 @@ import {
isPayToScriptHashTypeAddress,
fromSatoshiToTokenPrecision,
getSigner,
getGoerliDevelopmentContracts,
} from "../utils"
import {
Client,
Expand All @@ -32,16 +28,10 @@ import {
UnspentTransactionOutput,
} from "@keep-network/tbtc-v2.ts/dist/src/bitcoin"
import {
ElectrumClient,
EthereumBridge,
EthereumTBTCToken,
} from "@keep-network/tbtc-v2.ts/dist/src"
import {
BitcoinConfig,
BitcoinNetwork,
EthereumConfig,
UnspentTransactionOutputPlainObject,
} from "../types"
import { BitcoinConfig, BitcoinNetwork, EthereumConfig } from "../types"
import TBTCVault from "@keep-network/tbtc-v2/artifacts/TBTCVault.json"
import Bridge from "@keep-network/tbtc-v2/artifacts/Bridge.json"
import TBTCToken from "@keep-network/tbtc-v2/artifacts/TBTC.json"
Expand All @@ -54,7 +44,20 @@ import {
findWalletForRedemption,
} from "@keep-network/tbtc-v2.ts/dist/src/redemption"
import { TBTCToken as ChainTBTCToken } from "@keep-network/tbtc-v2.ts/dist/src/chain"
import { BitcoinUtxo, Deposit, TBTC as SDK, Hex } from "tbtc-sdk-v2"
import {
BitcoinUtxo,
Deposit,
TBTC as SDK,
Hex,
loadEthereumContracts,
ethereumNetworkFromSigner,
ethereumAddressFromSigner,
BitcoinClient,
DepositRequest,
ElectrumClient,
BitcoinTxHash,
BitcoinTx,
} from "tbtc-sdk-v2"
import { Web3Provider } from "@ethersproject/providers"

export enum BridgeActivityStatus {
Expand Down Expand Up @@ -208,9 +211,7 @@ export interface ITBTC {
* @param address - Bitcoin address UTXOs should be determined for.
* @returns List of UTXOs.
*/
findAllUnspentTransactionOutputs(
address: string
): Promise<UnspentTransactionOutput[]>
findAllUnspentTransactionOutputs(address: string): Promise<BitcoinUtxo[]>

/**
* Gets estimated fees that will be payed during a reveal and estimated amount
Expand Down Expand Up @@ -238,15 +239,15 @@ export interface ITBTC {
* @param utxo Deposit UTXO of the revealed deposit
* @returns Revealed deposit data.
*/
getRevealedDeposit(utxo: UnspentTransactionOutput): Promise<RevealedDeposit>
getRevealedDeposit(utxo: BitcoinUtxo): Promise<DepositRequest>

/**
* Gets the number of confirmations that a given transaction has accumulated
* so far.
* @param transactionHash Hash of the transaction.
* @returns The number of confirmations.
*/
getTransactionConfirmations(transactionHash: TransactionHash): Promise<number>
getTransactionConfirmations(transactionHash: BitcoinTxHash): Promise<number>

/**
* Gets the minimum number of confirmations needed for the minter to start the
Expand Down Expand Up @@ -334,7 +335,7 @@ export interface ITBTC {
* @param transactionHash Hash of the transaction.
* @returns Transaction object.
*/
getBitcoinTransaction(transactionHash: string): Promise<BitcoinTransaction>
getBitcoinTransaction(transactionHash: string): Promise<BitcoinTx>

/**
* Gets emitted `RedemptionRequested` events.
Expand Down Expand Up @@ -391,7 +392,7 @@ export interface ITBTC {
export class TBTC implements ITBTC {
private _bridge: EthereumBridge
private _tbtcVault: Contract
private _bitcoinClient: Client
private _bitcoinClient: BitcoinClient
private _multicall: IMulticall
private _bridgeContract: Contract
private _token: ChainTBTCToken
Expand Down Expand Up @@ -458,26 +459,54 @@ export class TBTC implements ITBTC {
ethereumConfig.providerOrSigner,
ethereumConfig.account
)
this._handleSDKInitialization(ethereumConfig)
this._handleSDKInitialization(ethereumConfig, bitcoinConfig)
}

private async _handleSDKInitialization(ethereumConfig: EthereumConfig) {
private async _handleSDKInitialization(
ethereumConfig: EthereumConfig,
bitcoinConfig: BitcoinConfig
) {
// TODO: Revamp SDK/Threshold lib initialization
const { providerOrSigner, account } = ethereumConfig
const signer =
// Double bang to convert to boolean
!!account && providerOrSigner instanceof Web3Provider
? getSigner(providerOrSigner as Web3Provider, account)
: providerOrSigner

const hasMockedBitcoinClient =
bitcoinConfig.client && !bitcoinConfig.credentials

if (hasMockedBitcoinClient) {
console.log("Using custom bitcoin client")
const depositorAddress = await ethereumAddressFromSigner(signer)
const ethereumNetwork = await ethereumNetworkFromSigner(signer)

const tbtcContracts =
getGoerliDevelopmentContracts(signer) ??
(await loadEthereumContracts(signer, ethereumNetwork))
const bitcoinClient = (
hasMockedBitcoinClient
? bitcoinConfig.client
: // It can be assumed, credentials are defined here
new ElectrumClient(bitcoinConfig.credentials!)
) as BitcoinClient

this._sdk = await SDK.initializeCustom(tbtcContracts, bitcoinClient)

depositorAddress &&
this._sdk?.deposits.setDefaultDepositor(depositorAddress)

console.log({ tbtcContracts, bitcoinClient })
return
}

const initailizeFunction =
this.bitcoinNetwork === BitcoinNetwork.Mainnet
? SDK.initializeMainnet
: SDK.initializeGoerli

const shouldUseSigner =
// Double bang to convert to boolean
!!account && providerOrSigner instanceof Web3Provider

this._sdk = await initailizeFunction(
shouldUseSigner
? getSigner(providerOrSigner as Web3Provider, account)
: providerOrSigner
)
this._sdk = await initailizeFunction(signer)
}

get sdk(): SDK {
Expand Down Expand Up @@ -518,7 +547,7 @@ export class TBTC implements ITBTC {

findAllUnspentTransactionOutputs = async (
address: string
): Promise<UnspentTransactionOutput[]> => {
): Promise<BitcoinUtxo[]> => {
return await this._bitcoinClient.findAllUnspentTransactionOutputs(address)
}

Expand Down Expand Up @@ -603,8 +632,9 @@ export class TBTC implements ITBTC {
revealDeposit = async (utxo: BitcoinUtxo): Promise<string> => {
const { value, ...transactionOutpoint } = utxo
const chainHash = await this.deposit.initiateMinting(transactionOutpoint)
console.log({ chainHash })

return chainHash.toString()
return chainHash.toPrefixedString()
// return await tBTCRevealDeposit(
// utxo,
// depositScriptParameters,
Expand All @@ -614,14 +644,19 @@ export class TBTC implements ITBTC {
// )
}

getRevealedDeposit = async (
utxo: UnspentTransactionOutput
): Promise<RevealedDeposit> => {
return await tBTCgetRevealedDeposit(utxo, this._bridge)
getRevealedDeposit = async (utxo: BitcoinUtxo): Promise<DepositRequest> => {
const deposit = await this._sdk!.tbtcContracts.bridge.deposits(
utxo.transactionHash,
utxo.outputIndex
)
if (!deposit) {
throw new Error("Deposit not found!")
}
return deposit
}

getTransactionConfirmations = async (
transactionHash: TransactionHash
transactionHash: BitcoinTxHash
): Promise<number> => {
return await this._bitcoinClient.getTransactionConfirmations(
transactionHash
Expand Down Expand Up @@ -937,6 +972,7 @@ export class TBTC implements ITBTC {
redeemerOutputScript,
this.bitcoinNetwork,
this._bridge,
//@ts-ignore
this._bitcoinClient
)
}
Expand Down Expand Up @@ -989,10 +1025,8 @@ export class TBTC implements ITBTC {

getBitcoinTransaction = async (
transactionHash: string
): Promise<BitcoinTransaction> => {
return this._bitcoinClient.getTransaction(
TransactionHash.from(transactionHash)
)
): Promise<BitcoinTx> => {
return this._bitcoinClient.getTransaction(Hex.from(transactionHash))
}

getRedemptionRequestedEvents = async (
Expand Down
5 changes: 3 additions & 2 deletions src/threshold-ts/utils/bitcoin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
Network,
validate,
} from "bitcoin-address-validation"
import { BitcoinTxHash, Hex } from "tbtc-sdk-v2"

export const BITCOIN_PRECISION = 8

Expand Down Expand Up @@ -43,8 +44,8 @@ export const isPayToScriptHashTypeAddress = (address: string): boolean => {
* @param {string} txHash Transaction hash as string.
* @return {TransactionHash} Reversed transaction hash.
*/
export const reverseTxHash = (txHash: string): TransactionHash => {
return TransactionHash.from(txHash).reverse()
export const reverseTxHash = (txHash: string): BitcoinTxHash => {
return Hex.from(txHash).reverse()
}

export const prependScriptPubKeyByLength = (scriptPubKey: string) => {
Expand Down
37 changes: 37 additions & 0 deletions src/threshold-ts/utils/contract.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { JsonRpcSigner, Web3Provider, BlockTag } from "@ethersproject/providers"
import { Contract, ContractInterface, providers, Signer, Event } from "ethers"
import { AddressZero, getAddress, isAddressZero } from "./address"
import {
EthereumBridge,
EthereumTBTCToken,
EthereumTBTCVault,
EthereumWalletRegistry,
TBTCContracts,
} from "tbtc-sdk-v2"
import { getEnvVariable } from "../../utils/getEnvVariable"
import { EnvVariable } from "../../enums"

// account is not optional
export function getSigner(
Expand Down Expand Up @@ -66,3 +75,31 @@ export function getContractAddressFromTruffleArtifact(
).address
: AddressZero
}

export const getGoerliDevelopmentContracts = (
signerOrProvider: Signer | providers.Provider
): TBTCContracts => {
const useGoerliDevelopmentContracts =
getEnvVariable(EnvVariable.USE_GOERLI_DEVELOPMENT_CONTRACTS) === "true"

return useGoerliDevelopmentContracts
? {
bridge: new EthereumBridge({
address: "0xB07051CE2A47b58C22bdfD1425BCEad27F6072Db",
signerOrProvider,
}),
tbtcToken: new EthereumTBTCToken({
address: "0xd33b90D2c792F00d3746eF29cBE9aa0aAef915E1",
signerOrProvider,
}),
tbtcVault: new EthereumTBTCVault({
address: "0x0099960098f5A5343Bef3185e7E365d3a558D36a",
signerOrProvider,
}),
walletRegistry: new EthereumWalletRegistry({
address: "0x18930D71C7aE52beCB474A39173Def1A09b861a0",
signerOrProvider,
}),
}
: ({} as TBTCContracts)
}

0 comments on commit d51cbfc

Please sign in to comment.