# Webhook Alerts for Cypher Business

Now businesses can configure webhooks under Settings -> Alerts -> Setup Webhook menu on the top right.&#x20;

Configure a hook URL which can accept HTTP POST Request with the following payloads.&#x20;

## Sample Payloads

### **Different Event Types**

`type: 'DEBIT' | 'CREDIT' | 'REFUND' | 'DECLINE' | 'LOW_BALANCE_ALERT' | 'DAILY_BALANCE_ALERT'`

### Debit Response<br>

```
JSON
{
	id: string,
	type: string,
	amount: number,
	date: string(ISO format),
	isSettled: boolean,
	title: string,
	category: string,
	last4: string,
	closingBalance: number,
	employeeName: string,
};
```

### Credit Response

```
JSON
{
	id: string,
	type: string,
	amount: number,
	date: string(ISO format),
	title: string,
	closingBalance: number,
	tokenData: {
		chain: string,
		hash: string,
		symbol: string,
		tokenNos: string,
	}
}
```

### Refund Response

```
JSON
{
	id: string,
	type: string,
	amount: number,
	date: string(ISO format),
	isSettled: boolean,
	title: string,
	category: string,
	last4: string,
	closingBalance: number,
	employeeName: string,
}
```

### Decline Response

```
JSON
{
	id: string,
	type: string,
	amount: number,
	date: string(ISO format),
	title: string,
	category: string,
	last4: string,
	closingBalance: number,
	employeeName: string,
	reason: string,
}
```

### Low Balance Alert Response

```
JSON
{
	type: string,
	date: string(ISO format),
	closingBalance: number,
	lowBalanceLimit: number,
	businessName: string,
}
```

### Daily Balance Alert Response

```
JSON
{
	type: string,
	date: string(ISO format),
	closingBalance: number,
	businessName: string,
}
```


# Cypher On-Boarding SDK

Cypher On-Boarding SDK was created to solve the Cold Start Problem in dApp User Onboarding where users have to rely on 3rd party sources for on-ramp, bridging and go through a steep learning curve.

Immediately after the user connects the wallet, Cypher On-Boarding SDK with just a line of code intelligently understands the context of the user on multiple-chains and suggests different options in which they can bridge or on-ramp the necessary token before using the dApp.&#x20;

### Example Code Snippet

```html
<script src="https://public.cypherd.io/sdk/cypher-sdk.js"></script>
```

```javascript
// For Testnet

window.Cypher({ 
  address: '0xdEc1bc71bf91431D60eF2742f412DCd1c5A204B8',
  targetChainIdHex: '0x5', // Eth - Goerli
  requiredTokenBalance: 65,
  isTestnet: true,
  theme:'light',
  callBack: () => { console.log('callBack called'); }
});


// For Mainnet 

window.Cypher({
  appId: '<<app id for your account>>' 
  address: '0xdEc1bc71bf91431D60eF2742f412DCd1c5A204B8',
  targetChainIdHex: '0x1', // Ethereum
  requiredTokenBalance: 0.1,
  callBack: () => { console.log('callBack called'); }
});

```

| Args                         | Value                              | Description                                                                                                                                                |
| ---------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| appId                        | STRING : UUID                      | <p>Optional (but required for production development) to unlock partner benefits. <br><br>Reachout to us on support(at)cypherwallet(dot)io get the key</p> |
| \*address                    | STRING                             | User wallet address                                                                                                                                        |
| \*targetChainIdHex           | STRING                             | Chain ID in hex                                                                                                                                            |
| \*requiredTokenBalance       | Number                             | Token value                                                                                                                                                |
| requiredTokenContractAddress | STRING: Optional                   | Native Currency by default or ERC-20 contract address                                                                                                      |
| isTestnet                    | Boolean: Optional                  | Default: False, When enabled only testnets will be included.                                                                                               |
| callBack (boolean)           | Function: Optional                 | Callback function will be triggered at the end of the onboarding workflow with boolean value                                                               |
| theme                        | Enum : 'light' \| 'dark'           | UI theme. Dark mode by default                                                                                                                             |
| connector                    | walletconnect's connector instance | applicable only for walletconnect                                                                                                                          |
| provider                     | walletconnect's provider instance  | applicable only for walletconnect                                                                                                                          |
| showInfoScreen               | Boolean                            | <p>Defaults to <code>false.</code><br><br>To show users an intro page to set context on this operation. </p>                                               |
| parentComponentId            | STRING: Optional                   | <p>Default: '' ( empty string )<br></p><p>ONLY NEEDED IN CASE OF WIDGET.</p>                                                                               |

Add the above snippet of \<script> tag to import the necessary SDK into your dApp's \<head> tag. Then as soon as the user Connects wallet and the dApp has access to the user's wallet address listen to the necessary event and trigger the window\.Cypher() with the user's wallet address and the necessary token required to use the dApp.&#x20;

There are two ways to integrate the SDK into your dApp. You can choose the mode based on your preference and use case:

1. **Pop-up Modal:**&#x20;

   The SDK will be added as a pop-up modal that will only be triggered if the user has a balance in the `requiredToken` less than the `requiredTokenBalance`. This mode allows for a more dynamic and on-demand interaction with the SDK.
2. **Widget**:&#x20;

   The SDK will be added as a widget that is always present inside a designated `<div>` tag of your dApp. In this mode, the SDK will be permanently visible and accessible to users, regardless of their token balance. This mode provides a consistent and readily available user experience, allowing users to interact with the SDK at any time.

**POP-UP MODE:**

In this mode, the On-Boarding SDK appears only if the user does not have the necessary token to use the dApp.&#x20;

If the user does not have the necessary token to use the dApp, a modal similar to the one shown below will appear, displaying a list of tokens that the user has on other chains and providing various options for converting that token to the necessary token in the target chain that the dApp supports.

<figure><img src="https://728555026-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjlEooGohHZf4M6VXG5T2%2Fuploads%2FDEfRM4zWaxQ6itSs19zp%2FScreenshot%202023-07-13%20at%203.35.01%20PM.png?alt=media&amp;token=86b7c3ac-4dcc-435f-a0a7-d0bd4e8852eb" alt=""><figcaption><p>Cypher On-Boarding SDK as pop-up modal</p></figcaption></figure>

**WIDGET MODE:**

In this mode, the On-Boarding SDK will be always present inside the designated `<div>` tag of your dApp. Pass the id of the `<div>` in which you want to embed the widget as value to the `parentComponentId` parameter in the window\.Cypher() call. The `to chain` and `to token` will be locked to the chain and token contract address that you provide. The `from chain` and `from token` can be chosen from a list of tokens in which the user has balance.

<figure><img src="https://728555026-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjlEooGohHZf4M6VXG5T2%2Fuploads%2FHGsGJyOnHHCkZJAXsg9B%2FScreenshot%202023-07-13%20at%203.23.06%20PM.png?alt=media&amp;token=4f186af7-96ff-4bdc-8f68-b18a5c0b1524" alt=""><figcaption><p>Cypher On-Boarding SDK as widget</p></figcaption></figure>

#### DEMO

{% embed url="<https://www.loom.com/share/fb4a3fd37fcf47f1a87593e43db3bbaf>" %}

The SDK automatically detects the window\.etherum object for injected web3 and generates a transaction and routes it to the connected wallet. The routing is currently being powered by Cypher's proprietary bridge technology that sources liquidity through DEXs on different chains. Will add more options in the future. Cypher's bridge technology has been powering the Cypher Wallet Users for the last 1 year to seamlessly bridge across multiple EVM and Cosmos chains (coming soon). Support for other bridges, DEX, Exchanges and On-Ramp Providers coming soon. <https://cypherwallet.io>

#### ChainId List

* 0x1 - Ethereum
* 0x89 - Polygon
* 0x38 - Binance Smart Chain
* 0xa86a - Avalanche C-Chain
* 0xfa - Fantom
* 0x2329 - EVMOS
* 0xa4b1 - Arbitrum
* 0xa - Optimism
* 0x5 - Ethereum Goerli (Testnet)
* 0x13881 - Polygon Mumbai (Testnet)


# Cypher Push Notification SDK

**Note:** This is an evolving SDK, if you have any suggestions are recommendation feel free to propose improvements by publishing a PR updating Improvements section below.

## Cypher Wallet Push SDK

### Context

A blockchain user interested to know latest earnings or updates to their wallet intertactions through a decentralized application (dApp) must first vist the dApp through a web-3 enabled browser and connect the wallet. Once connected, the user can navigate to the section of the dApp that displays information of their interest. The dApp will then interact with the blockchain to retrieve the user's wallet data, such as the current balance and transaction history. The dApp will display this information to the user in a user-friendly format, allowing them to see their updated wallet information. The user can then use this information to make informed decisions about their cryptocurrency transactions. dApp developers have to rely on events form the smart contracts or poll for updates so the latest data can be shown to the user.

A push notification alerting the users is helpful instead of regularly checking for updates as mentioned above.

### Notifying dApp users

This documentation is targeted at dApp developers to implement logic transforming the on-chain events to user-friendly readable notification messages. Developers can focus on transformation logic and leverage the Cypher Wallet Push SDK to handle notifying the users on their preferred channel linked to the Wallet address.

## How it works?

If a visual learner, refer to the video below

{% embed url="<https://www.youtube.com/watch?v=_q-N_3rJdBs>" %}
Push SDK Video Demo
{% endembed %}

A dApp developer would contribute to this package by writing the transformation logic as a simple TypeScript class adhering to the format defined below:

1. Create a new folder under [handlers](https://github.com/CypherD-IO/web3-event-parser/tree/main/src/handlers) directory for your dapp.
2. Create a new class which `extends BaseEventHandler`
3. Implement following two abstract methods
   1. `getContractDetails(): ContractDetail[]` should return Chain and Contract Address of interest for your handler
   2. `getEventsToRegister(): EventNameWithHandler[];` should return events and corresponding handler methods to be invoked.
4. `handler` methods for each event should adhere to following return format:

   <https://github.com/CypherD-IO/web3-event-parser/blob/main/src/model/baseEventHandler.ts#L44-L52>

   Note: You can return an array of `NotificationDetail` if you intend to send different messages for different user.
5. Your handler input parameters will be of format defined below: <https://github.com/CypherD-IO/web3-event-parser/blob/main/src/model/baseEventHandler.ts#L54-L59> Note: `eventData` field will be mathcing the ABI event signature defined.
6. Testing of your handler can be done by manually triggering as show in sample below: <https://github.com/CypherD-IO/web3-event-parser/blob/main/src/core/Web3EventEmitter.ts#L8-L18>

#### How to get the test event data to trigger?

To get the event signature data for testing purposes from a blockchain event emitted by a contract, you can follow these steps:

1. Determine the name of the event that you want to test. This information should be available in the contract code.
2. Find the event signature data by hashing the event's name and its input parameter types using the keccak-256 hashing algorithm. You can use an online tool such as Remix to do this.
3. In Remix, go to the "Compile" tab and select your contract. Then, click on the event that you want to test to see its signature data.
4. Copy the event signature data and use it in your testing framework to listen for the event.
5. Once you have the event signature data, use the provided script.

```typescript
import { ethers } from 'ethers';

const provider = ethers.getDefaultProvider('mainnet');

const contractAddress = '0x123...'; // Replace with your contract address
const contractAbi = [...] // Replace with your contract ABI
const eventSignature = '0x123...'; // Replace with your event signature data

const contract = new ethers.Contract(contractAddress, contractAbi, provider);

const filter = {
    fromBlock: 0,
    topics: [eventSignature]
};

contract.on('MyEvent', filter, (event) => {
    console.log(event);
});
```

#### Example

For a USDC Transfer event it looks like

```typescript
  { 
    contract: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174',
    eventName: 'Transfer',
    eventData: {
      from: string,
      to: string,
      value: BigNumber
      }
  }
```

The output of this function would be of the following format:

```typescript
[
  {
    address: '0x2',
    title: 'USDC trasnfer',
    message: 'You have received 19 USDC token from 0x1.',
    options: { url: 'www.cypherwallet.io' }
  },
  {
    address: '0x1',
    title: 'USDC trasnfer',
    message: 'You have transferred 19 USDC token from 0x1 to 0x2.',
    options: { url: 'www.cypherwallet.io' }
  }
]
```

### Event types

#### Direct user transfer events

A wallet address deposited or withdrawn a specific token. Ex: A LP token issued(transferred) to User's wallet address for providing liquidity.

**Notificatoin Address:** Present in the event data.

#### Protocol token holder events

A Protocol token representing some underlying tokens could change which doesnt involve Users wallet address. Ex: A LP Token generated yield which can only be fetched by interacting with Smart Contract(read) by the User's wallet address.

**Notificatoin Address:** User's wallet address needs to be determined based on the Protocol token holders.

#### DApp notifications (NOT SUPPORTED YET)

Updates or promotions from the dApp to notify interested users. Ex: Updates on APY changes for a Liquidity Protocol

**Notificatoin Address:** User's wallet address determined by Push SDK based on user subscription preference.

### Testing

#### Unit testing using Jest

Unit testing involves testing individual modules or functions in isolation. In the case of the Event Handler package, each module can be tested individually by providing mock event data and ensuring that the function produces the expected output.

#### Integration testing (TBD)

Integration testing can be done by passing in a real event data to the SDK which invokes the dApp custom event handler. The output of notification message will be seen as the response to validate. This will not be sending any notification to users.

## Architecture:

The application is built using an event-driven architecture, where events are received from an external system and then processed by the application. The application is divided into two packages to separate the Core logic from the Event Handler logic. This allows for easy maintenance and scalability of the application.

The Core package is responsible for parsing the event data and invoking the corresponding event handler. The event handler is then invoked with the parsed event data, and it processes the event as required. The input format of the event handler is defined based on the event type. For a USDC Transfer event it looks like

```typescript
  { 
    contract: '0x2791bca1f2de4661ed88a30c99a7a9449aa84174',
    eventName: 'Transfer',
    eventData: {
      from: string,
      to: string,
      value: BigNumber
      }
  }
```

The Event Handler package contains the implementation of all the event handlers. Each event handler is a separate module that exports a function that processes the event data. When a new event handler is added, it needs to be registered by specifying the event type that it can handle which requires following inputs

1. Chain - Ex: POLYGON
2. Contract - Ex: 0x2791bca1f2de4661ed88a30c99a7a9449aa84174
3. Event name: as emitted by the event contract or its delegator.

Event handler functions are expected to parse the event and perform necessary data ingestion, tranformation to return the human readable notification message. The expected output of the function should follow the following format:

```typescript
{
    'address':<Address> // Wallet address to be notified
    'title': <string>, // Short title of the event
    'message': <string>, // Message to be shown on the notification
    'options': { // Use case specific options which would need updates on the consumer side of notification to handle
        'url': <string>,
    }
}
```

### Implementation:

The application is built using Typescript, which provides type safety and helps catch errors during compilation. The application runs on Node, which provides a lightweight and scalable runtime environment for the application.

The Core package uses the aws-lambda library to handle Lambda events. This library provides a Handler type that can be used to define the event handler function signature. The Core package defines a processEvent function that takes the event data and invokes the corresponding event handler based on the event type. The processEvent function uses a Map to store the registered event handlers and their corresponding event types.

The Event Handler package contains separate modules for each event handler. Each module exports a function that takes the parsed event data and processes it as required. The exported function is of the Handler type, which allows it to be registered with the Core package.

## Improvements

1. Add testing and validation steps


