Skip to content

Commit

Permalink
Merge pull request #278 from coinbase/CDF-3742-quickstart-guide
Browse files Browse the repository at this point in the history
fix(CDF-3742): Add to webhooks quickstart guide
  • Loading branch information
cb-davidlai authored Oct 2, 2024
2 parents bba7f47 + dba04b1 commit 69d8118
Show file tree
Hide file tree
Showing 6 changed files with 132 additions and 7 deletions.
25 changes: 24 additions & 1 deletion quickstart-template/README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
### Quickstart template for Platform SDK
# Quickstart template for Platform SDK

This is a template repository for quickly getting started with the Platform SDK. It provides a simple example of how to use the SDK.

## Create a Wallet, Fund, and Transfer

To set up the template, run the following commands:

```bash
npm install
npm run start
Expand All @@ -15,6 +16,7 @@ This command will create a developer-custodial wallet, deposit testnet funds to
## Trade Assets

To set up the template, run the following commands:

```bash
npm install
npm run start-trade-assets
Expand All @@ -25,6 +27,7 @@ This command will create a developer-custodial wallet on Base Mainnet and trade
## Mass Payout

To set up the template, run the following commands:

```bash
npm install
npm run start-mass-payout
Expand All @@ -38,6 +41,7 @@ If you don't already have a URL setup for event notification,
you can follow these [instructions to setup a simple Webhook App](./webhook/README.md).

To set up the template, run the following commands:

```bash
npm install
npm run start-webhook
Expand All @@ -46,3 +50,22 @@ npm run start-webhook
This command will demonstrate how to create a webhook for ERC20 transfer events on USDC.

You can also use [CDP Portal](https://portal.cdp.coinbase.com/products/webhooks) for Webhook configurations.

### Webhook - transfer between wallets

We also have a template for setting up two wallets and a webhook and receiving the transfer information between those two wallets on your webhook.

To set up the template, run the following commands:

```bash
npm install
npm run start-webhook-wallet-transfer
```

On this template, we'll demonstrate how to do a ERC20 transfer between two wallets and receive that transfer on your webhook.

_Note: Although usually transactions are sent to webhook within a minute, it may take several minutes for it to be sent to the webhook._

You can find more information about webhooks in the [documentation](https://docs.cdp.coinbase.com/onchain-data/docs/webhooks).

_____________________
1 change: 1 addition & 0 deletions quickstart-template/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"start-trade-assets": "node trade-assets.js",
"start-mass-payout": "node mass-payout.js",
"start-webhook": "node webhook.js",
"start-webhook-wallet-transfer": "node webhook-wallet-transfer.js",
"start-register-basename": "node register-basename.js"
},
"keywords": [],
Expand Down
90 changes: 90 additions & 0 deletions quickstart-template/webhook-wallet-transfer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { Coinbase, Wallet, Webhook } from "@coinbase/coinbase-sdk";

// Change this to the path of your API key file downloaded from CDP portal.
Coinbase.configureFromJson({ filePath: "~/Downloads/cdp_api_key.json" });

// Create wallets for transferring funds between each other
let myWallet = await Wallet.create();
let anotherWallet = await Wallet.create();

console.log('Wallets created! ...');

// Wallets come with a single default Address, accessible via getDefaultAddress()
let myWalletAddress = await myWallet.getDefaultAddress();
let anotherWalletAddress = await anotherWallet.getDefaultAddress();

// Get both wallet addresses
const myWalletAddressId = myWalletAddress.getId();
const anotherWalletAddressId = anotherWalletAddress.getId();

console.log('Wallets addresses fetched! ...');

// Faucet wallet to add some funds
await myWallet.faucet(Coinbase.assets.Usdc); // USDC funds to actual transaction
await myWallet.faucet(Coinbase.assets.Eth); // ETH funds for transfer gas fee (USDC gas fee is charged in ETH)

console.log('Funds added to myWallet! ...');
console.log('Funds available on myWallet:', (await myWallet.listBalances()).toString());

// Let's create a webhook that will be triggered when a transfer happens between the two wallets created above
// Don't forget to replace the notificationUri and signatureHeader
let webhook = await Webhook.create({
networkId: 'base-sepolia', // Listening on sepolia testnet transactions
notificationUri: 'https://<your_webhook_uri>/callback', // Your webhook address
eventType: 'erc20_transfer',
eventFilters: [{
// Webhook will only be triggered when these filter criteria are met
from_address: myWalletAddressId,
to_address: anotherWalletAddressId,
}],
});

console.log(`\nWebhook successfully created: `, webhook.toString());

// You can fetch all the information used on webhook creation using getters functions:
console.log(`\nWebhook event filters: `, webhook.getEventFilters());
console.log(`Webhook event type: `, webhook.getEventType());
console.log(`Webhook network id: `, webhook.getNetworkId());
console.log(`Webhook notification URI: `, webhook.getNotificationURI());

console.log('\n\n------------------------------------------------------------------------------------------------------------------');
console.log(`Before transferring, please make sure you have your local server running:`);
console.log(`cd webhook && npm install && npm run start-webhook-app`);
console.log('------------------------------------------------------------------------------------------------------------------');
console.log('Please press Enter to continue...');
await waitForEnter();

console.log('Creating transfer...');
// Create transfer from myWallet to anotherWallet
const transfer = await myWallet.createTransfer({
amount: 0.0001,
assetId: Coinbase.assets.Usdc,
destination: anotherWallet,
// gasless: true, // for USDC, you can also add gasless flag, so you don't need to add ETH funds for paying for gas fees
});

// Wait for the transfer to complete or fail on-chain
await transfer.wait();
console.log(`Transfer successfully completed: `, transfer.toString());

// From the default address object, you can list the transaction that was just made:
// const transactions = (await myWalletAddress.listTransactions({})).transactions
// console.log('Transactions list', transactions);
// You can also get a specific transaction link to see transaction details
// transactions[0].getTransactionLink()

console.log('\n\n------------------------------------------------------------------------------------------------------------------');
console.log('Be aware that after transfer is successfully completed, it may take a few minutes for the webhook to be triggered.');
console.log('------------------------------------------------------------------------------------------------------------------');


function waitForEnter() {
return new Promise(resolve => {
process.stdin.on('data',function (chunk) {
if (chunk[0] === 10) {
resolve();
process.stdin.pause();
}
});
});
}
4 changes: 2 additions & 2 deletions quickstart-template/webhook.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Coinbase.configureFromJson({ filePath: "~/Downloads/cdp_api_key.json" });
// Be sure to update the uri to your webhook url
let webhook = await Webhook.create(
"base-mainnet",
"https://webhook.notification.url/callback",
"https://<your_webhook_uri>/callback",
"erc20_transfer",
[{ contract_address: "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913" }],
);
Expand All @@ -16,7 +16,7 @@ console.log(`Webhook successfully created: `, webhook.toString());
let webhooks = await Webhook.list();

// Iterate over all webhooks created
// You cna also see list of webhook from CDP Portal
// You can also see list of webhook from CDP Portal
// https://portal.cdp.coinbase.com/products/webhooks
for (const wh of webhooks) {
console.log(wh.toString());
Expand Down
14 changes: 10 additions & 4 deletions quickstart-template/webhook/README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
### Quickstart template for Webhook App
# Quickstart template for Webhook App

This is a template repository for quickly getting started with a Webhook App,
This is a template repository for quickly getting started with a Webhook App,
which can be used for setting up Webhooks for listening to blockchain event notifications.

## Local Webhook App

To set up the template, run the following commands from this `webhook` folder:

```bash
npm install
npm run start-webhook-app
Expand All @@ -14,6 +15,7 @@ npm run start-webhook-app
This command will set up a webhook app locally.

Once the local webhook app is setup, in another terminal window, you can test it with:

```bash
curl -X POST -H "Content-Type:application/json" -d '{"app": "webhook"}' http://localhost:3000/callback
```
Expand All @@ -22,15 +24,19 @@ curl -X POST -H "Content-Type:application/json" -d '{"app": "webhook"}' http://l

To setup a temporary public URL that points to this local webhook app,
you can use [Pinggy](https://pinggy.io/) in another terminal window:

```bash
ssh -p 443 -R0:localhost:3000 -L4300:localhost:4300 qr@a.pinggy.io
```

You can also use [Vercel](https://vercel.com/) or other hosting solutions for your webhook app.

Once the public webhook app is setup, copy the URL provided and test it with:

```bash
curl -X POST -H "Content-Type:application/json" -d '{"app": "webhook"}' {url_copied_from_pinggy_io}/callback
```
This URL (ie Notification URL) can now be used to create Webhook either
via [CDP Portal](https://docs-cdp-onchain-data-preview.cbhq.net/developer-platform/docs/cdp-webhooks/)

This URL (ie Notification URL) can now be used to create Webhook either
via [CDP Portal](https://docs-cdp-onchain-data-preview.cbhq.net/developer-platform/docs/cdp-webhooks/)
or [Coinbase SDK](https://docs-cdp-onchain-data-preview.cbhq.net/coinbase-sdk/docs/webhooks).
5 changes: 5 additions & 0 deletions quickstart-template/webhook/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ app.post("/callback", (req, res) => {
// here's what you'll expect to receive depending on the event type
// https://docs.cdp.coinbase.com/onchain-data/docs/webhooks#event-types
const data = req.body;

console.log('Headers received:');
console.log(JSON.stringify(req.headers, null, 4));
console.log('Body received:');
console.log(JSON.stringify(data, null, 4));

const response = {
message: "Data received",
received_data: data,
Expand Down

0 comments on commit 69d8118

Please sign in to comment.