# Webhook

Swapper Finance Deposits provides real-time webhook notifications to keep your application informed about completed deposit transactions.

### Quick Start

#### 1. Add Webhook URL

Include the `webhookUrl` parameter when integrating Swapper Finance Deposits:

```typescript
import { SwapperIframe } from '@swapper-finance/deposit-sdk';

const swapper = new SwapperIframe({
  container: '#swapper-container',
  integratorId: 'your-integrator-id',
  dstChainId: '8453',
  dstTokenAddr: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
  depositWalletAddress: '0x2A018F2506acaEEE2C10632514Fc5DCa9eE2c28A',
  webhookUrl: "https://domain/com/api/webhook" // <--- here
});
```

#### 2. Handle Notifications

Create an endpoint to receive webhook notifications:

```javascript
app.post('/webhooks/deposit', (req, res) => {
  const { eventId, eventType, data } = req.body;

  if (eventType === 'transaction.completed') {
    console.log('Swap completed:', data.txHash);
    // Update your database, notify users, etc.
  }

  res.json({ received: true });
});
```

#### 3. Requirements

* **HTTPS endpoint**&#x20;
* **Public accessibility** from the internet
* **Fast response** - Return HTTP 200 within 10 seconds

### Event Payload

Webhooks are sent as POST requests with JSON payloads:

```json
{
  "eventId": "uuid",
  "eventType": "transaction.completed",
  "timestamp": "2024-11-15T14:30:00.000Z",
  "data": {
    "jobId": "0xabcd...",
    "executionId": "173168...",
    "smartWalletAddress": "0x...",
    "chainId": "1",
    "status": "completed",
    "txHash": "0x...",
    "tokenAddress": "0x...",
    "amount": "1000000",
    "destinationChainId": "137",
    "destinationAddress": "0x...",
    "targetToken": "0x...",
    "integratorId": "your-id"
  }
}
```

#### Field Descriptions

| Field                     | Type   | Description                                |
| ------------------------- | ------ | ------------------------------------------ |
| `eventId`                 | string | Unique identifier for idempotency          |
| `eventType`               | string | Event type (`transaction.completed`)       |
| `timestamp`               | string | ISO 8601 timestamp of the event            |
| `data.jobId`              | string | Delegation job identifier                  |
| `data.executionId`        | string | Specific execution identifier              |
| `data.smartWalletAddress` | string | Smart wallet that executed the transaction |
| `data.chainId`            | string | Source blockchain ID                       |
| `data.txHash`             | string | Transaction hash on the blockchain         |
| `data.tokenAddress`       | string | Token contract address that was swapped    |
| `data.amount`             | string | Amount swapped (in smallest unit)          |
| `data.destinationChainId` | string | Destination blockchain ID                  |
| `data.destinationAddress` | string | Where funds are being sent                 |
| `data.targetToken`        | string | Target token on destination chain          |
| `data.integratorId`       | string | Your integrator identifier                 |

#### Webhook Signature Verification

All webhook requests include an `X-Webhook-Signature` header for security verification. This header contains an HMAC-SHA256 signature of the request payload using your integrator's secret key.

**How to Verify Signatures**

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

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('base64');

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  );
}

// In your webhook handler
app.post('/webhooks/deposit', (req, res) => {
  const signature = req.headers['x-webhook-signature'];
  const payload = JSON.stringify(req.body);
  const secret = process.env.SWAPPER_WEBHOOK_SECRET; // Your secret key

  if (!verifyWebhookSignature(payload, signature, secret)) {
    console.error('Invalid webhook signature');
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // Process webhook...
  res.json({ received: true });
});
```

**Getting Your Secret Key**

Contact Swapper support to receive your webhook secret key. This key should be:

* Stored securely (never in version control)
* Used only for webhook signature verification
* Rotated periodically for security

**Signature Details**

* **Algorithm**: HMAC-SHA256
* **Encoding**: Base64
* **Header**: `X-Webhook-Signature`
* **Payload**: Raw JSON string of the request body

### Troubleshooting

#### Common Issues

| Issue                        | Solution                                                  |
| ---------------------------- | --------------------------------------------------------- |
| **Not receiving webhooks**   | Verify endpoint is publicly accessible and returns 200    |
| **Duplicate events**         | Check `eventId` for idempotency                           |
| **Slow responses**           | Ensure 200 response within 10 seconds                     |
| **SSL certificate errors**   | Use valid HTTPS certificates                              |
| **Invalid signatures**       | Verify secret key and signature calculation               |
| **Missing signature header** | Contact support if `X-Webhook-Signature` header is absent |

### Support

If you encounter issues:

1. Check this documentation
2. Review your implementation against the examples
3. Contact support with:
   * Your `integratorId`
   * Example `eventId` (if applicable)
   * Recent log entries
   * Your webhook endpoint URL
   * Signature verification issues (include received signature and payload)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.swapper.finance/webhook.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
