Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: deposit-withdrawal #9

Merged
merged 23 commits into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
cf9980a
feat: add withdrawal transaction functions
Polybius93 Jun 13, 2024
1895913
feat: add comments, modify withdrawal transaction recipients
Polybius93 Jun 13, 2024
a390e15
change var name from closing to withdrawal
sosaucily Jun 18, 2024
ce0b159
feat: modify createWithdrawalPSBT function to check withdraw value
Polybius93 Jun 19, 2024
4cb8a7d
chore: merge branch 'main' into feat/withdrawal
Polybius93 Jun 19, 2024
9ac9b58
feat: add createWithdrawalPSBT function to PrivateKeyDLCHandler
Polybius93 Jun 19, 2024
0b4d913
feat: remove closingPSBT related functions
Polybius93 Jun 19, 2024
be7ce26
feat: add bitcoinAmount arguemnt to funding transaction handling func…
Polybius93 Jun 20, 2024
04903f3
Co-authored-by: Polybius93 <[email protected]>
sosaucily Jun 25, 2024
59e5e6c
feat: add deposit psbt functions
Polybius93 Jun 26, 2024
dea1fa3
feat: apply patch for additional withdraw related functions
Polybius93 Jun 26, 2024
ccdfded
feat: update deposit and withdraw functions
Polybius93 Jun 28, 2024
e8f044d
feat: add user input finalization function
Polybius93 Jun 28, 2024
a3f03f3
feat: modify ethereum handlers to match new dlc contracts
Polybius93 Jun 28, 2024
8309f51
add try catch for when there are no inputs
sosaucily Jun 28, 2024
962e317
change withdraw text to wd for withdraw deposit
sosaucily Jun 30, 2024
b8b3662
chore: merge branch 'main' into feat/withdrawal
Polybius93 Jul 1, 2024
243a283
adding dist for testability
sosaucily Jul 1, 2024
e865450
fix: payment creation in withdrawal flow
Polybius93 Jul 1, 2024
fabef27
chore: merge branch 'feat/withdrawal-extended' into feat/withdrawal
Polybius93 Jul 1, 2024
0faca08
feat: add back dist to gitignore, update package version
Polybius93 Jul 1, 2024
2d31520
feat: replace withdrawal naming with withdraw, modify attestor handle…
Polybius93 Jul 2, 2024
7adf4eb
feat: bump version, modify deposit address checking
Polybius93 Jul 2, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"type": "module",
"name": "dlc-btc-lib",
"version": "1.0.11",
"version": "1.0.13",
"description": "This library provides a comprehensive set of interfaces and functions for minting dlcBTC tokens on supported blockchains.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
41 changes: 35 additions & 6 deletions src/attestor-handlers/attestor-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,18 @@ export class AttestorHandler {

async createPSBTEvent(
vaultUUID: string,
fundingTransaction: string,
closingPSBT: string,
userNativeSegwitAddress: string
fundingTransactionPsbt: string,
mintAddress: string,
alicePubkey: string
): Promise<void> {
const createPSBTEndpoints = this.attestorRootURLs.map(url => `${url}/app/create-psbt-event`);

const body = JSON.stringify({
uuid: vaultUUID,
funding_transaction: fundingTransaction,
closing_psbt: closingPSBT,
mint_address: userNativeSegwitAddress,
funding_transaction_psbt: fundingTransactionPsbt,
mint_address: mintAddress,
chain: this.ethereumChainID,
alice_pubkey: alicePubkey,
});

const requests = createPSBTEndpoints.map(async url =>
Expand All @@ -48,4 +48,33 @@ export class AttestorHandler {
);
}
}

async submitWithdrawRequest(vaultUUID: string, withdrawPSBT: string): Promise<void> {
const withdrawEndpoints = this.attestorRootURLs.map(url => `${url}/app/withdraw`);

const body = JSON.stringify({
uuid: vaultUUID,
wd_psbt: withdrawPSBT,
});

const requests = withdrawEndpoints.map(async url =>
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
body,
})
.then(response => (response.ok ? true : response.statusText))
Polybius93 marked this conversation as resolved.
Show resolved Hide resolved
.catch(error => error.message)
);

const responses = await Promise.all(requests);

const failedResponses = responses.filter(response => response !== true);
Polybius93 marked this conversation as resolved.
Show resolved Hide resolved

if (failedResponses.length === withdrawEndpoints.length) {
throw new AttestorError(
`Error sending Withdraw Transaction to Attestors: ${failedResponses.join(', ')}`
);
}
}
}
2 changes: 1 addition & 1 deletion src/constants/ethereum-constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,4 @@ export const addNetworkParams = {

export const GITHUB_SOLIDITY_URL = 'https://raw.githubusercontent.com/DLC-link/dlc-solidity';

export const dlcContractNames: DLCEthereumContractName[] = ['TokenManager', 'DLCManager', 'DLCBTC'];
export const dlcContractNames: DLCEthereumContractName[] = ['DLCManager', 'DLCBTC'];
146 changes: 122 additions & 24 deletions src/dlc-handlers/ledger-dlc-handler.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { bytesToHex } from '@noble/hashes/utils';
import { Transaction } from '@scure/btc-signer';
import { P2Ret, P2TROut, p2tr, p2wpkh } from '@scure/btc-signer/payment';
import { Network, Psbt } from 'bitcoinjs-lib';
Expand All @@ -17,8 +18,9 @@ import {
import {
addNativeSegwitSignaturesToPSBT,
addTaprootInputSignaturesToPSBT,
createClosingTransaction,
createDepositTransaction,
createFundingTransaction,
createWithdrawalTransaction,
getNativeSegwitInputsToSign,
getTaprootInputsToSign,
updateNativeSegwitInputs,
Expand Down Expand Up @@ -130,6 +132,10 @@ export class LedgerDLCHandler {
return this.payment;
}

getTaprootDerivedPublicKey(): string {
return bytesToHex(this.getPayment().taprootDerivedPublicKey);
}

getVaultRelatedAddress(paymentType: 'funding' | 'multisig'): string {
const payment = this.getPayment();

Expand Down Expand Up @@ -280,6 +286,7 @@ export class LedgerDLCHandler {

async createFundingPSBT(
vault: RawVault,
bitcoinAmount: bigint,
attestorGroupPublicKey: string,
feeRateMultiplier?: number,
customFeeRate?: bigint
Expand Down Expand Up @@ -307,8 +314,8 @@ export class LedgerDLCHandler {
throw new Error('Insufficient Funds');
}

const fundingPSBT = await createFundingTransaction(
vault.valueLocked.toBigInt(),
const fundingTransaction = await createFundingTransaction(
bitcoinAmount,
this.bitcoinNetwork,
multisigPayment.address as string,
fundingPayment,
Expand All @@ -319,12 +326,12 @@ export class LedgerDLCHandler {
);

const signingConfiguration = createBitcoinInputSigningConfiguration(
fundingPSBT,
fundingTransaction,
this.walletAccountIndex,
this.bitcoinNetwork
);

const formattedFundingPSBT = Psbt.fromBuffer(Buffer.from(fundingPSBT), {
const formattedFundingPSBT = Psbt.fromBuffer(Buffer.from(fundingTransaction.toPSBT()), {
network: this.bitcoinNetwork,
});

Expand Down Expand Up @@ -361,25 +368,31 @@ export class LedgerDLCHandler {
}
}

async createClosingPSBT(
async createWithdrawalPSBT(
vault: RawVault,
withdrawAmount: bigint,
attestorGroupPublicKey: string,
fundingTransactionID: string,
feeRateMultiplier?: number,
customFeeRate?: bigint
): Promise<Psbt> {
try {
const { fundingPayment, multisigPayment, taprootDerivedPublicKey } = this.getPayment();
const { fundingPayment, taprootDerivedPublicKey, multisigPayment } = await this.createPayment(
vault.uuid,
attestorGroupPublicKey
);

if (fundingPayment.address === undefined) {
throw new Error('Could not get Addresses from Payments');
if (multisigPayment.address === undefined || fundingPayment.address === undefined) {
throw new Error('Payment Address is undefined');
}

const feeRate =
customFeeRate ??
BigInt(await getFeeRate(this.bitcoinBlockchainFeeRecommendationAPI, feeRateMultiplier));

const closingPSBT = createClosingTransaction(
vault.valueLocked.toBigInt(),
const withdrawalTransaction = await createWithdrawalTransaction(
this.bitcoinBlockchainAPI,
withdrawAmount,
this.bitcoinNetwork,
fundingTransactionID,
multisigPayment,
Expand All @@ -389,38 +402,109 @@ export class LedgerDLCHandler {
vault.btcRedeemFeeBasisPoints.toBigInt()
);

const closingTransactionSigningConfiguration = createBitcoinInputSigningConfiguration(
closingPSBT,
const withdrawalTransactionSigningConfiguration = createBitcoinInputSigningConfiguration(
withdrawalTransaction,
this.walletAccountIndex,
this.bitcoinNetwork
);

const formattedClosingPSBT = Psbt.fromBuffer(Buffer.from(closingPSBT), {
const formattedWithdrawalPSBT = Psbt.fromBuffer(Buffer.from(withdrawalTransaction.toPSBT()), {
network: this.bitcoinNetwork,
});

const closingInputByPaymentTypeArray = getInputByPaymentTypeArray(
closingTransactionSigningConfiguration,
formattedClosingPSBT.toBuffer(),
const withdrawalInputByPaymentTypeArray = getInputByPaymentTypeArray(
withdrawalTransactionSigningConfiguration,
formattedWithdrawalPSBT.toBuffer(),
this.bitcoinNetwork
);

const taprootInputsToSign = getTaprootInputsToSign(closingInputByPaymentTypeArray);
const taprootInputsToSign = getTaprootInputsToSign(withdrawalInputByPaymentTypeArray);

await updateTaprootInputs(
taprootInputsToSign,
taprootDerivedPublicKey,
this.masterFingerprint,
formattedClosingPSBT
formattedWithdrawalPSBT
);

return formattedClosingPSBT;
return formattedWithdrawalPSBT;
} catch (error: any) {
throw new Error(`Error creating Closing PSBT: ${error}`);
throw new Error(`Error creating Withdrawal PSBT: ${error}`);
}
}

async createDepositPSBT(
depositAmount: bigint,
vault: RawVault,
attestorGroupPublicKey: string,
fundingTransactionID: string,
feeRateMultiplier?: number,
customFeeRate?: bigint
) {
const { fundingPayment, taprootDerivedPublicKey, fundingDerivedPublicKey, multisigPayment } =
await this.createPayment(vault.uuid, attestorGroupPublicKey);

if (multisigPayment.address === undefined || fundingPayment.address === undefined) {
throw new Error('Payment Address is undefined');
}

const feeRate =
customFeeRate ??
BigInt(await getFeeRate(this.bitcoinBlockchainFeeRecommendationAPI, feeRateMultiplier));

const depositTransaction = await createDepositTransaction(
this.bitcoinBlockchainAPI,
this.bitcoinNetwork,
depositAmount,
fundingTransactionID,
multisigPayment,
fundingPayment,
feeRate,
vault.btcFeeRecipient,
vault.btcMintFeeBasisPoints.toBigInt()
);

const depositTransactionSigningConfiguration = createBitcoinInputSigningConfiguration(
depositTransaction,
this.walletAccountIndex,
this.bitcoinNetwork
);

const formattedDepositPSBT = Psbt.fromBuffer(Buffer.from(depositTransaction.toPSBT()), {
network: this.bitcoinNetwork,
});

const withdrawalInputByPaymentTypeArray = getInputByPaymentTypeArray(
depositTransactionSigningConfiguration,
formattedDepositPSBT.toBuffer(),
this.bitcoinNetwork
);

const taprootInputsToSign = getTaprootInputsToSign(withdrawalInputByPaymentTypeArray);
const nativeSegwitInputsToSign = getNativeSegwitInputsToSign(withdrawalInputByPaymentTypeArray);

await updateTaprootInputs(
taprootInputsToSign,
taprootDerivedPublicKey,
this.masterFingerprint,
formattedDepositPSBT
);

await updateNativeSegwitInputs(
nativeSegwitInputsToSign,
fundingDerivedPublicKey,
this.masterFingerprint,
formattedDepositPSBT,
this.bitcoinBlockchainAPI
);

return formattedDepositPSBT;
}

async signPSBT(psbt: Psbt, transactionType: 'funding' | 'closing'): Promise<Transaction> {
async signPSBT(
psbt: Psbt,
transactionType: 'funding' | 'deposit' | 'withdraw'
): Promise<Transaction> {
try {
const { fundingWalletPolicy, multisigWalletPolicy, multisigWalletPolicyHMac } =
this.getPolicyInformation();
Expand All @@ -444,13 +528,27 @@ export class LedgerDLCHandler {
transaction = Transaction.fromPSBT(psbt.toBuffer());
transaction.finalize();
return transaction;
case 'closing':
case 'deposit':
signatures = await this.ledgerApp.signPsbt(
psbt.toBase64(),
multisigWalletPolicy,
multisigWalletPolicyHMac
);
addTaprootInputSignaturesToPSBT('funding', psbt, signatures);

signatures = await this.ledgerApp.signPsbt(psbt.toBase64(), fundingWalletPolicy, null);

addNativeSegwitSignaturesToPSBT(psbt, signatures);

transaction = Transaction.fromPSBT(psbt.toBuffer());
return transaction;
case 'withdraw':
signatures = await this.ledgerApp.signPsbt(
psbt.toBase64(),
multisigWalletPolicy,
multisigWalletPolicyHMac
);
addTaprootInputSignaturesToPSBT('closing', psbt, signatures);
addTaprootInputSignaturesToPSBT('withdraw', psbt, signatures);
transaction = Transaction.fromPSBT(psbt.toBuffer());
return transaction;
default:
Expand Down
Loading
Loading