# Commerce Onchain Protocol

The [Commerce Onchain Payment Protocol](https://github.com/coinbase/commerce-onchain-payment-protocol) is an open-source project designed to facilitate the integration of on-chain cryptocurrency payments into e-commerce platforms. This protocol provides a standardized way to handle payments directly on blockchain networks, leveraging smart contracts and blockchain addresses for secure and transparent transactions.

#### Overview of Commerce Onchain Payment Protocol

The protocol aims to provide a consistent interface and process for accepting cryptocurrency payments. Here’s a breakdown of how it works and its key components:

#### Key Components

1. **Payment Address Generation**: Unique blockchain addresses are generated for each payment.
2. **Transaction Monitoring**: Transactions to these addresses are monitored for confirmation.
3. **Smart Contracts**: Used to handle the payment logic and ensure funds are correctly transferred.
4. **Webhooks**: Notifications are sent to the merchant’s server when payments are received and confirmed.

#### How It Works

1. **Initiate Payment**:
   * When a customer decides to pay with cryptocurrency, a unique payment address is generated for the transaction.
   * This address is provided to the customer to send the payment.
2. **Monitor Transactions**:
   * The protocol monitors the blockchain for transactions to the generated address.
   * Once a transaction is detected, it is tracked until it receives the required number of confirmations.
3. **Confirm Payment**:
   * After the transaction is confirmed, the funds are considered successfully received.
   * The merchant is notified of the payment via a webhook or API call.
4. **Smart Contract Integration**:
   * Smart contracts can be used to automate the payment process, ensuring that the funds are securely handled.
   * These contracts can handle additional logic such as refunds, escrow, and multi-signature approvals.

#### Implementing the Protocol

**Step 1: Generate a Payment Address**

The first step is to generate a unique address for each payment. This can be done using an HD wallet or a similar method to ensure that each transaction has a unique address.

**Example Using Ethers.js (Ethereum):**

```javascript
const { ethers } = require('ethers');

// Create an HD wallet from a mnemonic
const mnemonic = 'your mnemonic phrase here';
const masterNode = ethers.utils.HDNode.fromMnemonic(mnemonic);

const generateEthereumAddress = (index) => {
    const childNode = masterNode.derivePath(`m/44'/60'/0'/0/${index}`);
    return {
        address: childNode.address,
        privateKey: childNode.privateKey
    };
};

const { address, privateKey } = generateEthereumAddress(0);
console.log(`Generated Ethereum Address: ${address}`);
```

**Step 2: Monitor the Payment Address**

Next, monitor the generated address for incoming transactions. This can be done using blockchain APIs or services like Alchemy, Infura, or directly interacting with the blockchain.

**Example Using Alchemy Webhooks:**

1. **Set Up Webhook Endpoint**:

   ```javascript
   const express = require('express');
   const app = express();
   app.use(express.json());

   app.post('/webhook', (req, res) => {
       const event = req.body;
       console.log('New transaction event:', event);
       // Handle the event (e.g., update database, notify user)
       res.status(200).send('Event received');
   });

   app.listen(3000, () => {
       console.log('Server running on port 3000');
   });
   ```
2. **Register Address for Monitoring**:

   ```javascript
   const axios = require('axios');

   const registerAddressForMonitoring = async (address, webhookUrl) => {
       const response = await axios.post(
           'https://eth-mainnet.alchemyapi.io/v2/YOUR_ALCHEMY_API_KEY',
           {
               addresses: [address],
               webhookUrl: webhookUrl,
               event: 'NEW_TRANSACTION'
           }
       );
       console.log('Address registered:', response.data);
   };

   // Register address for monitoring
   registerAddressForMonitoring('0xYourEthereumAddress', 'https://your-server.com/webhook');
   ```

**Step 3: Confirm the Payment**

After detecting the transaction, wait for the required number of confirmations before considering the payment complete.

**Example Using Ethers.js:**

```javascript
const waitForConfirmations = async (txHash, confirmations = 12) => {
    const receipt = await provider.waitForTransaction(txHash, confirmations);
    return receipt;
};

const receipt = await waitForConfirmations(transactionHash);
if (receipt.status) {
    console.log('Transaction confirmed:', receipt);
    // Notify merchant and fulfill order
}
```

**Step 4: Notify the Merchant**

Once the payment is confirmed, notify the merchant through a webhook or API call.

**Example Notification:**

```javascript
const notifyMerchant = (transactionDetails) => {
    // Implement notification logic (e.g., send an HTTP request to the merchant's server)
    console.log('Notify merchant:', transactionDetails);
};

notifyMerchant(receipt);
```

#### Conclusion

The Commerce Onchain Payment Protocol provides a robust framework for integrating cryptocurrency payments into e-commerce platforms. By generating unique addresses, monitoring transactions, and using smart contracts, merchants can securely accept and manage cryptocurrency payments. This approach ensures transparency, security, and efficiency in handling on-chain transactions. If you need further details or have specific questions about implementing this protocol, feel free to ask!
