Skip to content

Commit

Permalink
Feature/tt 610 sdk bnb (#637)
Browse files Browse the repository at this point in the history
* TT-610 sdk support for bnb + examples

* TT-610 sdk support for bnb + examples

* TT-610 sdk support for bnb + examples

* TT-610 sdk support for bnb + examples

* TT-610 sdk support for bnb + examples

* TT-610 bnb sdsk

* TT-610 bnb sdsk

* TT-610 bnb sdsk

* TT-610 - fixes

* TT-610 - fixes

Co-authored-by: Sceri <scerimail@gmail.com>
  • Loading branch information
jhammer-tatum and Sceri committed Nov 7, 2022
1 parent e030e3d commit ba0977f
Show file tree
Hide file tree
Showing 40 changed files with 1,677 additions and 470 deletions.
56 changes: 56 additions & 0 deletions examples/bnb-example/README.md
@@ -0,0 +1,56 @@
# How to use TatumSDK with Binance beacon chain

These examples should guide you through some basic operations of the BNB blockchain. You will be able to:

- generate BNB wallet
- check the balance of the wallet
- send BNB to another wallet
- perform blockchain queries such as getting specific block or transaction information

## How to start

In order to start, you need to create an API Key at [Tatum Dashboard](https://dashboard.tatum.io).

You need to install the @tatum/bnb package from npm.

```bash
npm install @tatumio/bnb
```

or

```bash
yarn add @tatumio/bnb
```

At the end, you need to initialize new SDK with your API Key.

```typescript
import { TatumBnbSDK } from '@tatumio/bnb'

const bnbSDK = TatumBnbSDK({ apiKey: '75ea3138-d0a1-47df-932e-acb3ee807dab' })
```

Examples are written in TypeScript, but you can use them in JavaScript as well. We are following ES6 standard, so you
need to have Node.js version 10 or higher.

### How to generate a BNB wallet

```typescript
const bnbSDK = TatumBnbSDK({ apiKey: '75ea3138-d0a1-47df-932e-acb3ee807dab' })

const { address, privateKey } = await bnbSDK.wallet.generateWallet(true)
console.log(`My public address is ${address}, with private key ${privateKey}.`)
```

### How to send transaction to another wallet

You can find examples [here](./src/app/bnb.tx.example.ts).

### How to read information from the blockchain

You can find examples [here](./src/app/bnb.blockchain.example.ts).

### How to generate virtual account for BNB and transfer from it to a blockchain address

You can find examples [here](./src/app/bnb.virtualAccount.example.ts).
14 changes: 14 additions & 0 deletions examples/bnb-example/jest.config.js
@@ -0,0 +1,14 @@
module.exports = {
displayName: 'bnb-example',
preset: '../../jest.preset.js',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
},
},
transform: {
'^.+\\.[tj]s$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/examples/bnb-example',
}
5 changes: 5 additions & 0 deletions examples/bnb-example/package.json
@@ -0,0 +1,5 @@
{
"name": "@tatumio/bnb-example",
"version": "0.0.1",
"type": "commonjs"
}
32 changes: 32 additions & 0 deletions examples/bnb-example/project.json
@@ -0,0 +1,32 @@
{
"sourceRoot": "examples/bnb-example/src",
"projectType": "application",
"targets": {
"build": {
"executor": "@nrwl/webpack:webpack",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/examples/bnb-example",
"main": "examples/bnb-example/src/index.ts",
"tsConfig": "examples/bnb-example/tsconfig.app.json",
"packageJson": "examples/bnb-example/package.json",
"target": "node",
"compiler": "tsc"
}
},
"serve": {
"executor": "@nrwl/node:node",
"options": {
"buildTarget": "bnb-example:build"
}
},
"lint": {
"executor": "@nrwl/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": ["examples/bnb-example/**/*.ts"]
}
}
},
"tags": ["type:example"]
}
22 changes: 22 additions & 0 deletions examples/bnb-example/src/app/bnb.blockchain.example.ts
@@ -0,0 +1,22 @@
import { TatumBnbSDK } from '@tatumio/bnb'

const bnbSDK = TatumBnbSDK({ apiKey: '75ea3138-d0a1-47df-932e-acb3ee807dab' })

export async function bnbBlockchainExample() {
// Get BNB current block number
// https://apidoc.tatum.io/tag/BNB-Beacon-Chain#operation/BnbGetCurrentBlock
const currentBlockNumber = await bnbSDK.blockchain.getCurrentBlock()
console.log(`Current block: ${currentBlockNumber}`)

// Get block details
// https://apidoc.tatum.io/tag/BNB-Beacon-Chain#operation/BnbGetBlock
const block = await bnbSDK.blockchain.getBlock(currentBlockNumber - 1)
console.log(`Block Details: ${JSON.stringify(block)}`)

// Get BNB Transaction details by hash
// https://apidoc.tatum.io/tag/BNB-Beacon-Chain#operation/BnbGetTransaction
const transaction = await bnbSDK.blockchain.getTransaction(
'356BEBE84893CD8F3B130B0B2798FA3E3B199344981CF1C776A37D903F1D150F',
)
console.log(`Transaction Details: ${JSON.stringify(transaction)}`)
}
33 changes: 33 additions & 0 deletions examples/bnb-example/src/app/bnb.tx.example.ts
@@ -0,0 +1,33 @@
import { TatumBnbSDK } from '@tatumio/bnb'
import { Currency } from '@tatumio/api-client'

const bnbSDK = TatumBnbSDK({ apiKey: '75ea3138-d0a1-47df-932e-acb3ee807dab' })

export async function bnbTxExample() {
// Generate BNB wallet
// https://apidoc.tatum.io/tag/BNB-Beacon-Chain#operation/BnbGenerateWallet
const { address, privateKey } = await bnbSDK.wallet.generateWallet(true)
console.log(`My public address is ${address}, with private key ${privateKey}.`)

const { address: toAddress } = await bnbSDK.wallet.generateWallet(true)

// FUND YOUR ACCOUNT WITH BNB ACCORDING TO: https://docs.bnbchain.org/docs/wallet/binance/

// https://apidoc.tatum.io/tag/BNB-Beacon-Chain#operation/BnbGetAccount
const accountDetails = await bnbSDK.blockchain.getAccount(address)
console.log(`My account has balances: ${JSON.stringify(accountDetails.balances)}.`)

// Send BNB transaction
// https://apidoc.tatum.io/tag/BNB-Beacon-Chain#operation/BnbBlockchainTransfer
const txId = await bnbSDK.transaction.sendTransaction(
{
amount: '0.01',
to: toAddress,
fromPrivateKey: privateKey,
currency: Currency.BNB,
},
{ testnet: true },
)

console.log(`Transaction with ID ${JSON.stringify(txId)} was sent.`)
}
43 changes: 43 additions & 0 deletions examples/bnb-example/src/app/bnb.virtualAccount.examples.ts
@@ -0,0 +1,43 @@
import { TatumBnbSDK } from '@tatumio/bnb'
import { Currency } from '@tatumio/api-client'

const bnbSDK = TatumBnbSDK({ apiKey: '75ea3138-d0a1-47df-932e-acb3ee807dab' })

export async function bnbVirtualAccountExample() {
const { address, privateKey } = await bnbSDK.wallet.generateWallet(true)
const { address: to } = await bnbSDK.wallet.generateWallet(true)

console.log(`My public address is ${address}, with private key ${privateKey}.`)

// Generate new virtual account for BNB with specific blockchain address
// Each BNB virtual account must have MEMO field generated - take a look here for more details - https://docs.tatum.io/guides/ledger-and-off-chain/how-to-set-up-virtual-accounts-with-xrp-bnb-and-xlm
// No MEMO is created with this operation, only virtual account
// https://apidoc.tatum.io/tag/Account#operation/createAccount
const virtualAccount = await bnbSDK.ledger.account.create({
currency: Currency.BNB,
xpub: address,
})
console.log(JSON.stringify(virtualAccount))

// we need to generate MEMO - which is a deposit address - for this virtual account
// https://apidoc.tatum.io/tag/Blockchain-addresses#operation/generateDepositAddress
const depositAddress = await bnbSDK.virtualAccount.depositAddress.create(virtualAccount.id)

console.log(JSON.stringify(depositAddress))
// Result of the operation is combination of deposit address and MEMO
console.log(`Deposit address is ${depositAddress.address} with MEMO ${depositAddress.derivationKey}`)

// // FUND YOUR ACCOUNT WITH BNB ACCORDING TO: https://docs.bnbchain.org/docs/wallet/binance/

// I want to send assets from virtualAccount to blockchain address
// https://apidoc.tatum.io/tag/Blockchain-operations#operation/BnbTransfer
const result = await bnbSDK.virtualAccount.sendTransactionFromVirtualAccountToBlockchain(true, {
senderAccountId: virtualAccount.id,
amount: '0.001',
address: to,
attr: 'OPTIONAL_RECIPIENT_MEMO',
fromPrivateKey: privateKey,
})

console.log(JSON.stringify(result))
}
17 changes: 17 additions & 0 deletions examples/bnb-example/src/app/bnb.wallet.example.ts
@@ -0,0 +1,17 @@
import { TatumBnbSDK } from '@tatumio/bnb'

const bnbSDK = TatumBnbSDK({ apiKey: '75ea3138-d0a1-47df-932e-acb3ee807dab' })

export async function bnbWalletExample() {
// Generate BNB wallet
// https://apidoc.tatum.io/tag/BNB-Beacon-Chain#operation/BnbGenerateWallet
const { address, privateKey } = await bnbSDK.wallet.generateWallet(true)

console.log(`My public address is ${address}, with private key ${privateKey}.`)

// FUND YOUR ACCOUNT WITH BNB ACCORDING TO: https://docs.bnbchain.org/docs/wallet/binance/

// https://apidoc.tatum.io/tag/BNB-Beacon-Chain#operation/BnbGetAccount
const accountDetails = await bnbSDK.blockchain.getAccount(address)
console.log(`My account has ${JSON.stringify(accountDetails.balances)} BNB.`)
}
13 changes: 13 additions & 0 deletions examples/bnb-example/src/index.ts
@@ -0,0 +1,13 @@
/**
* This is example app, which shows how to use BNB SDK. For more details, see README or checkout our documentation at https://apidoc.tatum.io/tag/BNB-Beacon-Chain
*/

import { bnbWalletExample } from './app/bnb.wallet.example'
import { bnbBlockchainExample } from './app/bnb.blockchain.example'
import { bnbTxExample } from './app/bnb.tx.example'
import { bnbVirtualAccountExample } from './app/bnb.virtualAccount.examples'

console.log(`Running ${bnbWalletExample()}`)
console.log(`Running ${bnbTxExample()}`)
console.log(`Running ${bnbBlockchainExample()}`)
console.log(`Running ${bnbVirtualAccountExample()}`)
10 changes: 10 additions & 0 deletions examples/bnb-example/tsconfig.app.json
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"declaration": true,
"types": []
},
"include": ["**/*.ts"],
"exclude": ["**/*.spec.ts"]
}
22 changes: 22 additions & 0 deletions examples/bnb-example/tsconfig.json
@@ -0,0 +1,22 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "CommonJS",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}
9 changes: 9 additions & 0 deletions examples/bnb-example/tsconfig.spec.json
@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"include": ["**/*.test.ts", "**/*.spec.ts", "**/*.d.ts"]
}
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -33,6 +33,7 @@
"postinstall": "yarn patch:dependencies"
},
"dependencies": {
"@binance-chain/javascript-sdk": "^4.1.1",
"@celo-tools/celo-ethers-wrapper": "^0.1.0",
"@elrondnetwork/erdjs": "^9.2.4",
"@harmony-js/crypto": "^0.1.56",
Expand Down
8 changes: 4 additions & 4 deletions packages/api-client/src/generated/core/OpenAPI.ts
@@ -1,10 +1,10 @@
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ApiRequestOptions } from './ApiRequestOptions';
import type { ApiRequestOptions } from './ApiRequestOptions'

type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
type Headers = Record<string, string>;
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>
type Headers = Record<string, string>

type Config = {
BASE: string;
Expand All @@ -28,4 +28,4 @@ export const OpenAPI: Config = {
PASSWORD: undefined,
HEADERS: undefined,
ENCODE_PATH: undefined,
};
};
12 changes: 3 additions & 9 deletions packages/api-client/src/generated/core/request.ts
Expand Up @@ -34,15 +34,11 @@ const isBlob = (value: any): value is Blob => {
typeof value.constructor.name === 'string' &&
/^(Blob|File)$/.test(value.constructor.name) &&
/^(Blob|File)$/.test(value[Symbol.toStringTag])
);
};
)
}

function isFile(value: any): value is File {
return (
typeof value.name === 'string' &&
typeof value.lastModified === 'number' &&
isBlob(value)
)
return typeof value.name === 'string' && typeof value.lastModified === 'number' && isBlob(value)
}

function isSuccess(status: number): boolean {
Expand Down Expand Up @@ -254,7 +250,6 @@ export function request<T>(options: ApiRequestOptions): CancelablePromise<T> {
const response = await sendRequest(options, url, formData, body, headers, onCancel)
const responseBody = getResponseBody(response)
const responseHeader = getResponseHeader(response, options.responseHeader)

const result: ApiResult = {
url,
ok: isSuccess(response.status),
Expand All @@ -264,7 +259,6 @@ export function request<T>(options: ApiRequestOptions): CancelablePromise<T> {
}

catchErrors(options, result)

resolve(result.body)
}
} catch (error) {
Expand Down

0 comments on commit ba0977f

Please sign in to comment.