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 1 commit
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
99 changes: 49 additions & 50 deletions src/attestor-handlers/attestor-handler.ts
Original file line number Diff line number Diff line change
@@ -1,79 +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,
fundingTransactionPsbt: string,
mintAddress: string,
alicePubkey: 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_psbt: fundingTransactionPsbt,
mint_address: mintAddress,
chain: this.ethereumChainID,
alice_pubkey: alicePubkey,
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);

const failedResponses = responses.filter(response => response !== true);

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 [Funding] Transaction to Attestors:
${attestorResponses.join('| ')}`
);
}
}

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

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

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))
.catch(error => error.message)
const attestorResponses: (boolean | string)[] = await Promise.all(
depositWithdrawEndpoints.map(async url =>
this.sendRequest(url, body)
.then(response => response)
.catch(error => error.message)
)
);

const responses = await Promise.all(requests);

const failedResponses = responses.filter(response => response !== true);

if (failedResponses.length === withdrawEndpoints.length) {
if (attestorResponses.every(response => response !== true)) {
throw new AttestorError(
`Error sending Withdraw Transaction to Attestors: ${failedResponses.join(', ')}`
`Error sending [Deposit/Withdraw] Transaction to Attestors:
${attestorResponses.join('| ')}`
);
}
}
Expand Down
61 changes: 23 additions & 38 deletions src/dlc-handlers/ledger-dlc-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
addTaprootInputSignaturesToPSBT,
createDepositTransaction,
createFundingTransaction,
createWithdrawalTransaction,
createWithdrawTransaction,
getNativeSegwitInputsToSign,
getTaprootInputsToSign,
updateNativeSegwitInputs,
Expand Down Expand Up @@ -297,32 +297,25 @@ 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 fundingTransaction = await createFundingTransaction(
bitcoinAmount,
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(
Expand Down Expand Up @@ -368,7 +361,7 @@ export class LedgerDLCHandler {
}
}

async createWithdrawalPSBT(
async createWithdrawPSBT(
vault: RawVault,
withdrawAmount: bigint,
attestorGroupPublicKey: string,
Expand All @@ -382,54 +375,50 @@ export class LedgerDLCHandler {
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 withdrawalTransaction = await createWithdrawalTransaction(
const withdrawTransaction = await createWithdrawTransaction(
this.bitcoinBlockchainAPI,
withdrawAmount,
this.bitcoinNetwork,
withdrawAmount,
fundingTransactionID,
multisigPayment,
fundingPayment.address,
fundingPayment,
feeRate,
vault.btcFeeRecipient,
vault.btcRedeemFeeBasisPoints.toBigInt()
);

const withdrawalTransactionSigningConfiguration = createBitcoinInputSigningConfiguration(
withdrawalTransaction,
const withdrawTransactionSigningConfiguration = createBitcoinInputSigningConfiguration(
withdrawTransaction,
this.walletAccountIndex,
this.bitcoinNetwork
);

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

const withdrawalInputByPaymentTypeArray = getInputByPaymentTypeArray(
withdrawalTransactionSigningConfiguration,
formattedWithdrawalPSBT.toBuffer(),
const withdrawInputByPaymentTypeArray = getInputByPaymentTypeArray(
withdrawTransactionSigningConfiguration,
formattedWithdrawPSBT.toBuffer(),
this.bitcoinNetwork
);

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

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

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

Expand All @@ -444,10 +433,6 @@ export class LedgerDLCHandler {
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));
Expand All @@ -474,14 +459,14 @@ export class LedgerDLCHandler {
network: this.bitcoinNetwork,
});

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

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

await updateTaprootInputs(
taprootInputsToSign,
Expand Down
39 changes: 12 additions & 27 deletions src/dlc-handlers/private-key-dlc-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
import {
createDepositTransaction,
createFundingTransaction,
createWithdrawalTransaction,
createWithdrawTransaction,
} from '../functions/bitcoin/psbt-functions.js';
import { PaymentInformation } from '../models/bitcoin-models.js';
import { RawVault } from '../models/ethereum-models.js';
Expand Down Expand Up @@ -213,14 +213,7 @@ export class PrivateKeyDLCHandler {
attestorGroupPublicKey
);

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

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');
Expand All @@ -231,20 +224,20 @@ export class PrivateKeyDLCHandler {
BigInt(await getFeeRate(this.bitcoinBlockchainFeeRecommendationAPI, feeRateMultiplier));

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

return fundingTransaction;
}

async createWithdrawalPSBT(
async createWithdrawPSBT(
vault: RawVault,
withdrawAmount: bigint,
attestorGroupPublicKey: string,
Expand All @@ -258,28 +251,24 @@ export class PrivateKeyDLCHandler {
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 withdrawalTransaction = await createWithdrawalTransaction(
const withdrawTransaction = await createWithdrawTransaction(
this.bitcoinBlockchainAPI,
withdrawAmount,
this.bitcoinNetwork,
withdrawAmount,
fundingTransactionID,
multisigPayment,
fundingPayment.address!,
fundingPayment,
feeRate,
vault.btcFeeRecipient,
vault.btcRedeemFeeBasisPoints.toBigInt()
);
return withdrawalTransaction;
return withdrawTransaction;
} catch (error: any) {
throw new Error(`Error creating Withdrawal PSBT: ${error}`);
throw new Error(`Error creating Withdraw PSBT: ${error}`);
}
}

Expand Down Expand Up @@ -325,10 +314,6 @@ export class PrivateKeyDLCHandler {
attestorGroupPublicKey
);

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

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