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 all 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.14",
"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
88 changes: 58 additions & 30 deletions src/attestor-handlers/attestor-handler.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,78 @@
import {
FundingTXAttestorInfo,
WithdrawDepositTXAttestorInfo,
} from 'src/models/attestor.models.js';

import { AttestorError } from '../models/errors.js';

export class AttestorHandler {
private attestorRootURLs: string[];
private ethereumChainID: string;

constructor(
attestorRootURLs: string[],
ethereumChainID: 'evm-arbitrum' | 'evm-arbsepolia' | 'evm-localhost'
) {
constructor(attestorRootURLs: string[]) {
this.attestorRootURLs = attestorRootURLs;
this.ethereumChainID = ethereumChainID;
}

async createPSBTEvent(
vaultUUID: string,
fundingTransaction: string,
closingPSBT: string,
userNativeSegwitAddress: string
): Promise<void> {
const createPSBTEndpoints = this.attestorRootURLs.map(url => `${url}/app/create-psbt-event`);
private async sendRequest(url: string, body: string): Promise<boolean | string> {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
body,
});
if (!response.ok) {
throw new AttestorError(`Attestor Response ${url} was not OK: ${response.statusText}`);
}
return true;
}

async submitFundingPSBT(fundingTXAttestorInfo: FundingTXAttestorInfo): Promise<void> {
const fundingEndpoints = this.attestorRootURLs.map(url => `${url}/app/create-psbt-event`);

const body = JSON.stringify({
uuid: vaultUUID,
funding_transaction: fundingTransaction,
closing_psbt: closingPSBT,
mint_address: userNativeSegwitAddress,
chain: this.ethereumChainID,
uuid: fundingTXAttestorInfo.vaultUUID,
funding_transaction_psbt: fundingTXAttestorInfo.fundingPSBT,
mint_address: fundingTXAttestorInfo.userEthereumAddress,
chain: fundingTXAttestorInfo.attestorChainID,
alice_pubkey: fundingTXAttestorInfo.userBitcoinTaprootPublicKey,
});

const requests = createPSBTEndpoints.map(async url =>
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
body,
})
.then(response => (response.ok ? true : response.statusText))
.catch(error => error.message)
const attestorResponses: (boolean | string)[] = await Promise.all(
fundingEndpoints.map(async url =>
this.sendRequest(url, body)
.then(response => response)
.catch(error => error.message)
)
);

const responses = await Promise.all(requests);
if (attestorResponses.every(response => response !== true)) {
throw new AttestorError(
`Error sending [Funding] Transaction to Attestors:
${attestorResponses.join('| ')}`
);
}
}

async submitWithdrawDepositPSBT(
withdrawDepositTXAttestorInfo: WithdrawDepositTXAttestorInfo
): Promise<void> {
const depositWithdrawEndpoints = this.attestorRootURLs.map(url => `${url}/app/withdraw`);

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

const failedResponses = responses.filter(response => response !== true);
const attestorResponses: (boolean | string)[] = await Promise.all(
depositWithdrawEndpoints.map(async url =>
this.sendRequest(url, body)
.then(response => response)
.catch(error => error.message)
)
);

if (failedResponses.length === createPSBTEndpoints.length) {
if (attestorResponses.every(response => response !== true)) {
throw new AttestorError(
`Error sending Funding and Closing Transaction to Attestors: ${failedResponses.join(', ')}`
`Error sending [Deposit/Withdraw] Transaction to Attestors:
${attestorResponses.join('| ')}`
);
}
}
Expand Down
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'];
159 changes: 121 additions & 38 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,
createWithdrawTransaction,
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 All @@ -290,41 +297,34 @@ export class LedgerDLCHandler {
attestorGroupPublicKey
);

if ([multisigPayment.address, fundingPayment.address].some(x => x === undefined)) {
throw new Error('Payment Address is undefined');
}

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

const addressBalance = await getBalance(
fundingPayment.address as string,
this.bitcoinBlockchainAPI
);
const addressBalance = await getBalance(fundingPayment, this.bitcoinBlockchainAPI);

if (BigInt(addressBalance) < vault.valueLocked.toBigInt()) {
throw new Error('Insufficient Funds');
}

const fundingPSBT = await createFundingTransaction(
vault.valueLocked.toBigInt(),
const fundingTransaction = await createFundingTransaction(
this.bitcoinBlockchainAPI,
this.bitcoinNetwork,
multisigPayment.address as string,
bitcoinAmount,
multisigPayment,
fundingPayment,
feeRate,
vault.btcFeeRecipient,
vault.btcMintFeeBasisPoints.toBigInt(),
this.bitcoinBlockchainAPI
vault.btcMintFeeBasisPoints.toBigInt()
);

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,66 +361,135 @@ export class LedgerDLCHandler {
}
}

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

if (fundingPayment.address === undefined) {
throw new Error('Could not get Addresses from Payments');
}
const { fundingPayment, taprootDerivedPublicKey, multisigPayment } = await this.createPayment(
vault.uuid,
attestorGroupPublicKey
);

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

const closingPSBT = createClosingTransaction(
vault.valueLocked.toBigInt(),
const withdrawTransaction = await createWithdrawTransaction(
this.bitcoinBlockchainAPI,
this.bitcoinNetwork,
withdrawAmount,
fundingTransactionID,
multisigPayment,
fundingPayment.address,
fundingPayment,
feeRate,
vault.btcFeeRecipient,
vault.btcRedeemFeeBasisPoints.toBigInt()
);

const closingTransactionSigningConfiguration = createBitcoinInputSigningConfiguration(
closingPSBT,
const withdrawTransactionSigningConfiguration = createBitcoinInputSigningConfiguration(
withdrawTransaction,
this.walletAccountIndex,
this.bitcoinNetwork
);

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

const closingInputByPaymentTypeArray = getInputByPaymentTypeArray(
closingTransactionSigningConfiguration,
formattedClosingPSBT.toBuffer(),
const withdrawInputByPaymentTypeArray = getInputByPaymentTypeArray(
withdrawTransactionSigningConfiguration,
formattedWithdrawPSBT.toBuffer(),
this.bitcoinNetwork
);

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

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

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

async signPSBT(psbt: Psbt, transactionType: 'funding' | 'closing'): Promise<Transaction> {
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);

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 depositInputByPaymentTypeArray = getInputByPaymentTypeArray(
depositTransactionSigningConfiguration,
formattedDepositPSBT.toBuffer(),
this.bitcoinNetwork
);

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

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

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

return formattedDepositPSBT;
}

async signPSBT(
psbt: Psbt,
transactionType: 'funding' | 'deposit' | 'withdraw'
): Promise<Transaction> {
try {
const { fundingWalletPolicy, multisigWalletPolicy, multisigWalletPolicyHMac } =
this.getPolicyInformation();
Expand All @@ -444,13 +513,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