Skip to content
This repository has been archived by the owner on Jul 29, 2024. It is now read-only.

add BTC transactions page #35

Closed
wants to merge 4 commits into from
Closed

Conversation

mikelord007
Copy link

@mikelord007 mikelord007 commented Jun 30, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new interface for managing Bitcoin transactions, allowing users to interact with multiple wallet providers (XDefi, UniSat, XVerse) seamlessly.
    • Added functionality for creating and signing Bitcoin transactions on the testnet.
  • Bug Fixes

    • Implemented error handling to provide alerts for invalid inputs and wallet connection issues.
  • Chores

    • Updated project dependencies to enhance security and cryptocurrency functionalities.

Copy link

vercel bot commented Jun 30, 2024

@mikelord007 is attempting to deploy a commit to the Zeta Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

vercel bot commented Jun 30, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
example-frontend ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 30, 2024 5:32pm

Copy link
Member

@fadeev fadeev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mikelord007 please, fix TypeScript errors to make sure it builds with yarn build:

./app/btcintegration/page.tsx:53:28
Type error: Parameter 'params' implicitly has an 'any' type.

  51 |   }
  52 | 
> 53 |   const callXDefi = async (params) => {
     |                            ^
  54 |     if (!window.xfi) return alert("XDEFI wallet not installed")
  55 |     const wallet = window.xfi
  56 |     window.xfi.bitcoin.changeNetwork("testnet")
error Command failed with exit code 1.

@fadeev
Copy link
Member

fadeev commented Jun 30, 2024

Overall, I think it works. I ran out of testnet BTC while testing this, but seems like Xverse is creating a tx.

Xverse

Screenshot 2024-06-30 at 18 29 46 Screenshot 2024-06-30 at 18 29 49

Tx: c367cd678467d911c3b7c1b48c95aefaabd427636c655e3e80421b882ef33c5e (unconfirmed)

XDEFI

Screenshot 2024-06-30 at 18 30 47 Screenshot 2024-06-30 at 18 31 01

@fadeev
Copy link
Member

fadeev commented Jun 30, 2024

Hm, the issue with Xverse is that it's setting OP_RETURN as the first output. ZetaChain expects OP_RETURN to be the second output.

https://blockstream.info/testnet/tx/c367cd678467d911c3b7c1b48c95aefaabd427636c655e3e80421b882ef33c5e

Screenshot 2024-06-30 at 18 42 24

@fadeev
Copy link
Member

fadeev commented Jun 30, 2024

@lukema95 please, review.

Once this is merged, please, use this as a jumping-off point to add OKX support. Thanks!

@mikelord007
Copy link
Author

mikelord007 commented Jun 30, 2024

hey, have pushed fix for build errors and made OP_RETURN second output!
Lemme know if it's ready to merge so I can update the docs PR too

@fadeev
Copy link
Member

fadeev commented Jul 1, 2024

hey, have pushed fix for build errors and made OP_RETURN second output! Lemme know if it's ready to merge so I can update the docs PR too

I think it looks good, no further suggestions from me. Might need some time to get BTC to test again.

@fadeev
Copy link
Member

fadeev commented Jul 3, 2024

@mikelord007

Screenshot 2024-07-03 at 08 14 02 Screenshot 2024-07-03 at 08 14 10 Screenshot 2024-07-03 at 08 14 17

@fadeev
Copy link
Member

fadeev commented Jul 11, 2024

Related: secretkeylabs/sats-connect#143

@fadeev
Copy link
Member

fadeev commented Jul 15, 2024

@mikelord007 one last thing we need to take care of is formatting the contents of OP_RETURN in binary rather than UTF-8.

Here's an example of a successful transaction from Bitcoin (not using Xverse):

https://mempool.space/testnet/tx/995cdc393ac10ab90a53ca12abf291feabc94f9ba2c68fe9259f30498c2d4ff9

Notice, OP_RETURN %<NQ�CtQ,�!_.�{�aƾ�G ܘOBe�R>rmw�f^ — this may not look like much, but it's a correctly formatted memo in binary.

This, on the other hand, is incorrectly formatted (this is how the code in this PR works right now):

https://mempool.space/testnet/tx/d5ae072afa68df5105f4307bd9567bca37d11052661d959c3f2b7ac19e77f390

@lukema95
Copy link

lukema95 commented Jul 16, 2024

@mikelord007 @fadeev After I changed the code to look like this, I can sign multiple UTXOs normally:
https://mempool.space/testnet/tx/33f3e0ef6991f13dfda94998453e93ad84a5a5d4ea8a927625c5037548e09fb1

async function createTransaction(
  publickkey: string,
  senderAddress: string,
  params: Params
): Promise<{ psbtB64: string; utxoCnt: number }> {
  const publicKey = hex.decode(publickkey)

  const p2wpkh = btc.p2wpkh(publicKey, bitcoinTestnet)
  const p2sh = btc.p2sh(p2wpkh, bitcoinTestnet)

  const recipientAddress = "tb1qy9pqmk2pd9sv63g27jt8r657wy0d9ueeh0nqur"
  if (!senderAddress) {
    throw new Error("Error: no sender address")
  }
  if (!recipientAddress) {
    throw new Error("Error: no recipient address in ENV")
  }

  const output = await fetchUtxo(senderAddress)

  const tx = new btc.Transaction({
    allowUnknowOutput: true,
  })

  let utxoCnt = 0;

  output.forEach((utxo) => {
    tx.addInput({
      txid: utxo.txid,
      index: utxo.vout,
      witnessUtxo: {
        script: p2sh.script,
        amount: BigInt(utxo.value),
      },
      witnessScript: p2sh.witnessScript,
      redeemScript: p2sh.redeemScript,
    })
    utxoCnt += 1;
  })

  const changeAddress = senderAddress

  const memo = `${params.contract}${params.message}`.toLowerCase()

  const opReturn = btc.Script.encode(["RETURN", Buffer.from(memo, "utf8")])

  tx.addOutputAddress(recipientAddress, BigInt(params.amount), bitcoinTestnet)
  tx.addOutput({
    script: opReturn,
    amount: BigInt(0),
  })
  tx.addOutputAddress(changeAddress, BigInt(800), bitcoinTestnet)

  const psbt = tx.toPSBT(0)

  const psbtB64 = base64.encode(psbt)

  return {psbtB64, utxoCnt}
}
async function signPsbt(psbtBase64: string, utxoCnt: number, senderAddress: string) {
  // Get the PSBT Base64 from the input

  if (!psbtBase64) {
    alert("Please enter a valid PSBT Base64 string.")
    return
  }

  const sigInputs = new Array(utxoCnt).fill(0, 0, utxoCnt).map((_, i) => i);
  console.log("Sign inputs:", sigInputs)

  try {
    const response = await Wallet.request("signPsbt", {
      psbt: psbtBase64,
      allowedSignHash: btc.SignatureHash.ALL,
      broadcast: true,
      signInputs: {
        [senderAddress]: sigInputs,
      },
    })

    if (response.status === "success") {
      alert("PSBT signed successfully!")
    } else {
      if (response.error.code === RpcErrorCode.USER_REJECTION) {
        alert("Request canceled by user")
      } else {
        console.error("Error signing PSBT:", response.error)
        alert("Error signing PSBT: " + response.error.message)
      }
    }
  } catch (err) {
    console.error("Unexpected error:", err)
    alert("Error while signing")
  }
}

  const callXverse = async (params: Params) => {
    const response = await Wallet.request("getAccounts", {
      purposes: [AddressPurpose.Payment],
      message: "Test app wants to know your addresses!",
    })

    if (response.status == "success") {
      const result = await createTransaction(
        response.result[0].publicKey,
        response.result[0].address,
        params
      )

      await signPsbt(result.psbtB64, result.utxoCnt, response.result[0].address)
    } else {
      alert("wallet connection failed")
    }
  }

Copy link
Contributor

coderabbitai bot commented Jul 28, 2024

Walkthrough

Walkthrough

The recent updates introduce a comprehensive Bitcoin transaction integration feature within an application. A new component, BtcIntegration, facilitates user interactions with various Bitcoin wallets, allowing seamless transactions. Supporting utilities for transaction creation and signing enhance functionality, particularly on the testnet. Additionally, new dependencies strengthen security and transaction management capabilities. Overall, these changes significantly improve the application's ability to handle Bitcoin transactions effectively.

Changes

Files Change Summary
app/btcintegration/page.tsx Introduced a new React component BtcIntegration for Bitcoin transactions, which manages user inputs, wallet interactions, and transaction validation.
app/btcintegration/xverse-utils.ts Added functions createTransaction and signPsbt for managing Bitcoin transactions on the testnet, including PSBT creation and signing processes.
package.json Updated with new dependencies: @scure/base, micro-btc-signer, and sats-connect, enhancing security and cryptocurrency functionalities without removing existing packages.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant BtcIntegration
    participant WalletAPI
    participant XverseUtils

    User->>BtcIntegration: Enter transaction details
    BtcIntegration->>BtcIntegration: Validate inputs
    BtcIntegration->>WalletAPI: Select wallet & request connection
    WalletAPI-->>BtcIntegration: Connection status
    BtcIntegration->>XverseUtils: Create transaction
    XverseUtils-->>BtcIntegration: Return PSBT
    BtcIntegration->>WalletAPI: Sign PSBT
    WalletAPI-->>BtcIntegration: Signing status
    BtcIntegration-->>User: Show transaction outcome
Loading

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (5)
app/btcintegration/xverse-utils.ts (2)

14-31: Ensure Comprehensive Error Handling

The function fetchUtxo handles errors well, but consider adding more specific error messages for better debugging.

- throw new Error("Failed to fetch UTXO")
+ throw new Error(`Failed to fetch UTXO for address ${address}: ${response.statusText}`)

93-131: Use Consistent Error Handling

Ensure consistent error handling by providing more specific error messages and logging.

- alert("Error while signing")
+ alert(`Error while signing: ${err.message}`)
app/btcintegration/page.tsx (3)

66-94: Improve Error Handling in XDEFI Wallet Interaction

Consider providing more specific error messages for better debugging and user feedback.

- return alert(`Couldn't send transaction, ${JSON.stringify(err)}`)
+ return alert(`Couldn't send transaction: ${err.message}`)

96-107: Improve Error Handling in UniSat Wallet Interaction

Consider providing more specific error messages for better debugging and user feedback.

- return alert(`Couldn't send transaction, ${JSON.stringify(e)}`)
+ return alert(`Couldn't send transaction: ${e.message}`)

110-127: Improve Error Handling in Xverse Wallet Interaction

Consider providing more specific error messages for better debugging and user feedback.

- alert("wallet connection failed")
+ alert("Wallet connection failed. Please try again.")
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1aa945e and 91645df.

Files ignored due to path filters (2)
  • package-lock.json is excluded by !**/package-lock.json
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
Files selected for processing (3)
  • app/btcintegration/page.tsx (1 hunks)
  • app/btcintegration/xverse-utils.ts (1 hunks)
  • package.json (2 hunks)
Additional context used
Biome
app/btcintegration/page.tsx

[error] 13-13: Shouldn't redeclare 'Wallet'. Consider to delete it or rename it.

'Wallet' is defined here:

(lint/suspicious/noRedeclare)


[error] 43-43: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

Additional comments not posted (5)
package.json (3)

37-37: Dependency Addition: @scure/base

The @scure/base package has been added as a dependency. Ensure that this package is necessary and correctly used in the codebase.


56-56: Dependency Addition: micro-btc-signer

The micro-btc-signer package has been added as a dependency. Ensure that this package is necessary and correctly used in the codebase.


63-63: Dependency Addition: sats-connect

The sats-connect package has been added as a dependency. Ensure that this package is necessary and correctly used in the codebase.

app/btcintegration/xverse-utils.ts (2)

78-83: Optimize OP_RETURN Output Handling

The OP_RETURN output is correctly placed, but consider ensuring that the memo content is properly formatted as binary instead of UTF-8.

- const opReturn = btc.Script.encode(["RETURN", Buffer.from(memo, "utf8")])
+ const opReturn = btc.Script.encode(["RETURN", Buffer.from(memo, "binary")])

133-133: Export Statement

The export statement is correct and aligns with the functions defined in the file.

Comment on lines +34 to +91
async function createTransaction(
publickkey: string,
senderAddress: string,
params: Params
): Promise<{ psbtB64: string; utxoCnt: number }> {
const publicKey = hex.decode(publickkey)

const p2wpkh = btc.p2wpkh(publicKey, bitcoinTestnet)
const p2sh = btc.p2sh(p2wpkh, bitcoinTestnet)

const recipientAddress = "tb1qy9pqmk2pd9sv63g27jt8r657wy0d9ueeh0nqur"
if (!senderAddress) {
throw new Error("Error: no sender address")
}
if (!recipientAddress) {
throw new Error("Error: no recipient address in ENV")
}

const output = await fetchUtxo(senderAddress)

const tx = new btc.Transaction({
allowUnknowOutput: true,
})

let utxoCnt = 0

output.forEach((utxo) => {
tx.addInput({
txid: utxo.txid,
index: utxo.vout,
witnessUtxo: {
script: p2sh.script,
amount: BigInt(utxo.value),
},
witnessScript: p2sh.witnessScript,
redeemScript: p2sh.redeemScript,
})
utxoCnt += 1
})

const changeAddress = senderAddress

const memo = `${params.contract}${params.message}`.toLowerCase()

const opReturn = btc.Script.encode(["RETURN", Buffer.from(memo, "utf8")])
tx.addOutputAddress(recipientAddress, BigInt(params.amount), bitcoinTestnet)
tx.addOutput({
script: opReturn,
amount: BigInt(0),
})
tx.addOutputAddress(changeAddress, BigInt(800), bitcoinTestnet)

const psbt = tx.toPSBT(0)

const psbtB64 = base64.encode(psbt)

return { psbtB64, utxoCnt }
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typographical Error in Parameter Name

The parameter publickkey should be corrected to publicKey.

- publickkey: string,
+ publicKey: string,
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function createTransaction(
publickkey: string,
senderAddress: string,
params: Params
): Promise<{ psbtB64: string; utxoCnt: number }> {
const publicKey = hex.decode(publickkey)
const p2wpkh = btc.p2wpkh(publicKey, bitcoinTestnet)
const p2sh = btc.p2sh(p2wpkh, bitcoinTestnet)
const recipientAddress = "tb1qy9pqmk2pd9sv63g27jt8r657wy0d9ueeh0nqur"
if (!senderAddress) {
throw new Error("Error: no sender address")
}
if (!recipientAddress) {
throw new Error("Error: no recipient address in ENV")
}
const output = await fetchUtxo(senderAddress)
const tx = new btc.Transaction({
allowUnknowOutput: true,
})
let utxoCnt = 0
output.forEach((utxo) => {
tx.addInput({
txid: utxo.txid,
index: utxo.vout,
witnessUtxo: {
script: p2sh.script,
amount: BigInt(utxo.value),
},
witnessScript: p2sh.witnessScript,
redeemScript: p2sh.redeemScript,
})
utxoCnt += 1
})
const changeAddress = senderAddress
const memo = `${params.contract}${params.message}`.toLowerCase()
const opReturn = btc.Script.encode(["RETURN", Buffer.from(memo, "utf8")])
tx.addOutputAddress(recipientAddress, BigInt(params.amount), bitcoinTestnet)
tx.addOutput({
script: opReturn,
amount: BigInt(0),
})
tx.addOutputAddress(changeAddress, BigInt(800), bitcoinTestnet)
const psbt = tx.toPSBT(0)
const psbtB64 = base64.encode(psbt)
return { psbtB64, utxoCnt }
}
async function createTransaction(
publicKey: string,
senderAddress: string,
params: Params
): Promise<{ psbtB64: string; utxoCnt: number }> {
const publicKey = hex.decode(publicKey)
const p2wpkh = btc.p2wpkh(publicKey, bitcoinTestnet)
const p2sh = btc.p2sh(p2wpkh, bitcoinTestnet)
const recipientAddress = "tb1qy9pqmk2pd9sv63g27jt8r657wy0d9ueeh0nqur"
if (!senderAddress) {
throw new Error("Error: no sender address")
}
if (!recipientAddress) {
throw new Error("Error: no recipient address in ENV")
}
const output = await fetchUtxo(senderAddress)
const tx = new btc.Transaction({
allowUnknowOutput: true,
})
let utxoCnt = 0
output.forEach((utxo) => {
tx.addInput({
txid: utxo.txid,
index: utxo.vout,
witnessUtxo: {
script: p2sh.script,
amount: BigInt(utxo.value),
},
witnessScript: p2sh.witnessScript,
redeemScript: p2sh.redeemScript,
})
utxoCnt += 1
})
const changeAddress = senderAddress
const memo = `${params.contract}${params.message}`.toLowerCase()
const opReturn = btc.Script.encode(["RETURN", Buffer.from(memo, "utf8")])
tx.addOutputAddress(recipientAddress, BigInt(params.amount), bitcoinTestnet)
tx.addOutput({
script: opReturn,
amount: BigInt(0),
})
tx.addOutputAddress(changeAddress, BigInt(800), bitcoinTestnet)
const psbt = tx.toPSBT(0)
const psbtB64 = base64.encode(psbt)
return { psbtB64, utxoCnt }
}

const tss = "tb1qy9pqmk2pd9sv63g27jt8r657wy0d9ueeh0nqur"
if (contractAddress.length !== 42)
return alert("Not a valid contract address")
if (isUndefined(amount) || isNaN(amount))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use Number.isNaN for Type Safety

Replace isNaN with Number.isNaN to avoid type coercion issues.

- if (isUndefined(amount) || isNaN(amount))
+ if (isUndefined(amount) || Number.isNaN(amount))
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (isUndefined(amount) || isNaN(amount))
if (isUndefined(amount) || Number.isNaN(amount))
Tools
Biome

[error] 43-43: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

Comment on lines +33 to +63
const BtcIntegration = () => {
const [contractAddress, setContractAddress] = useState("")
const [message, setMessage] = useState("")
const [amount, setAmount] = useState<number | undefined>()
const [selectedWallet, setSelectedWallet] = useState<Wallet>("XDefi")

const sendTransaction = async () => {
const tss = "tb1qy9pqmk2pd9sv63g27jt8r657wy0d9ueeh0nqur"
if (contractAddress.length !== 42)
return alert("Not a valid contract address")
if (isUndefined(amount) || isNaN(amount))
return alert("Amount must be a number")

const params = {
contract: contractAddress.slice(2),
message: message.slice(2),
amount,
tss,
}

switch (selectedWallet) {
case "XDefi":
await callXDefi(params)
break
case "UniSat":
await callUniSat(params)
break
case "XVerse":
await callXverse(params)
break
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid Redeclaring 'Wallet'

The Wallet type is redeclared. Consider renaming it to avoid conflicts.

- type Wallet = "XDefi" | "UniSat" | "XVerse"
+ type WalletType = "XDefi" | "UniSat" | "XVerse"

Committable suggestion was skipped due to low confidence.

Tools
Biome

[error] 43-43: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@mikelord007
Copy link
Author

@lukema95 thanks for that, it successfully signs multiple UTXO's now
@fadeev not sure how to encode it to binary

@fadeev
Copy link
Member

fadeev commented Jul 29, 2024

@mikelord007 thanks for working on this! As the example frontend repo is getting deprecated, I've migrated the changes proposed in this PR into the UniversalKit repo: zeta-chain/universalkit#8

@fadeev fadeev closed this Jul 29, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants