Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Beta #84

Merged
merged 6 commits into from
May 28, 2024
Merged

Beta #84

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
"Typepoint",
"futurenet",
"Vals",
"Amoy"
"Amoy",
"Celo"
],
"flagWords": [],
"ignorePaths": [
Expand Down
148 changes: 77 additions & 71 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,21 @@ Provides an easy integration with the Allbridge Core ChainBridgeService for DApp

- [Installing](#installing)
- [How to use](#how-to-use)
- [1. Initialize SDK instance](#1-initialize-sdk-instance)
- [1. Initialize SDK instance](#1-initialize-sdk)
- [2. Get the list of supported tokens](#2-get-the-list-of-supported-tokens)
- [3.1 Approve the transfer of tokens](#31-approve-the-transfer-of-tokens)
- [3.1 Approve the transfer of tokens](#31-approve-the-transfer-of-tokens-only-for-evm-tron)
- [3.2 Send Tokens](#32-send-tokens)
- [Full example](#full-example)
- [Other operations](#other-operations)
- [Liquidity Pools operations](#liquidity-pools-operations)
- [Transaction builder](#transaction-builder)
- [Approve Transaction](#approve-transaction)
- [Send Transaction](#send-transaction)
- [Solana Blockchain](#solana-blockchain)
- [Get information about sent transaction](#get-information-about-sent-transaction)
- [Calculating amount of tokens to be received after fee](#calculating-amount-of-tokens-to-be-received-after-fee)
- [Calculating amount of tokens to send](#calculating-amount-of-tokens-to-send)
- [Getting the amount of gas fee](#getting-the-amount-of-gas-fee)
- [Getting the average transfer time](#getting-the-average-transfer-time)
- [Semver](#semver)

## Installing

Expand All @@ -45,29 +43,40 @@ $ npm install @allbridge/bridge-core-sdk

## How to use

### Find out how to integrate Allbridge Core SDK and Browser Extension Wallet

[***Evm***](https://github.com/allbridge-io/allbridge-core-js-sdk/tree/main/documentation/browser/evm.md)
[***Solana***](https://github.com/allbridge-io/allbridge-core-js-sdk/tree/main/documentation/browser/solana.md)
[***Stellar***](https://github.com/allbridge-io/allbridge-core-js-sdk/tree/main/documentation/browser/stellar.md)
[***Tron***](https://github.com/allbridge-io/allbridge-core-js-sdk/tree/main/documentation/browser/tron.md)

### 1. Initialize SDK
#### 1.1 Initialize SDK instance with your node Rpc urls (RECOMMENDED)

#### 1) Initialize SDK instance with your node Rpc urls (RECOMMENDED)

```ts
import { AllbridgeCoreSdk, nodeRpcUrlsDefault } from "@allbridge/bridge-core-sdk";
import {AllbridgeCoreSdk, nodeRpcUrlsDefault} from "@allbridge/bridge-core-sdk";
// Connections to blockchains will be made through your rpc-urls passed during initialization
const sdk = new AllbridgeCoreSdk({
...nodeRpcUrlsDefault,
TRX: "your trx-rpc-url",
ETH: "your eth-rpc-url"
});
// The Provider parameter may not be passed in methods where it is present, for example:
// Sdk will be using your rpc url for fetch data from blockchain to create tx
const rawTx = await sdk.bridge.rawTxBuilder.send(sendParams);
```

#### 1.2 Initialize SDK instance (using passed provider for blockchains connections)
#### 2) Initialize SDK instance (using passed provider for blockchains connections)

```ts
import { AllbridgeCoreSdk, nodeRpcUrlsDefault } from "@allbridge/bridge-core-sdk";
import {AllbridgeCoreSdk, nodeRpcUrlsDefault} from "@allbridge/bridge-core-sdk";

const sdk = new AllbridgeCoreSdk(nodeRpcUrlsDefault);
// The Provider parameter must be passed in order for it to be used to connect to the blockchain, for example:
const rawTx = await sdk.bridge.rawTxBuilder.send(sendParams, provider);
```

***TIP:*** Use 1.1 in case your provider differs from required by the SDK (Web3:v1.9.0, tronweb:v4.4.0)
***TIP:*** tested and developed for (Web3:v1.9.0, tronweb:v4.4.0), in other case use approach 1)

### 2. Get the list of supported tokens

Expand All @@ -79,16 +88,16 @@ const {bridgeAddress, tokens, chainId, name} = supportedChains[ChainSymbol.ETH];
const usdtOnEthToken = tokens.find(token => token.symbol === 'USDT');
```

### 3.1 Approve the transfer of tokens
### 3.1 Approve the transfer of tokens (only for Evm, Tron)

Before sending tokens, the bridge has to be authorized to use the tokens of the owner.
This is done by calling the `approve` method on SDK instance.</p>
This is done by building the `approve` transaction with SDK instance.</p>
For Ethereum USDT - due to specificity of the USDT contract:<br/>
If the current allowance is not 0,
this function will perform an additional transaction to set allowance to 0 before setting the new allowance value.

```ts
const response = await sdk.bridge.approve(provider, {
const rawTx = await sdk.bridge.rawTxBuilder.approve({
token: sourceToken,
owner: accountAddress
});
Expand All @@ -99,7 +108,7 @@ const response = await sdk.bridge.approve(provider, {
Initiate the transfer of tokens with `send` method on SDK instance.

```ts
sdk.bridge.send(provider, {
const rawTx = await sdk.bridge.rawTxBuilder.send({
amount: "1.01",
fromAccountAddress: fromAddress,
toAccountAddress: toAddress,
Expand All @@ -111,7 +120,7 @@ sdk.bridge.send(provider, {

### Full example

Swap BUSD on BSC chain to USDT on TRX chain
Swap USDC on ETH chain to USDC on POL chain

```ts
import {
Expand All @@ -121,50 +130,54 @@ import {
} from "@allbridge/bridge-core-sdk";
import Web3 from "web3";
import * as dotenv from "dotenv";
dotenv.config({ path: ".env" });
// Utils method
// For more details, see Examples (https://github.com/allbridge-io/allbridge-core-js-sdk/tree/main/examples)
// import { getEnvVar } from "../../../utils/env";
// import { sendEvmRawTransaction } from "../../../utils/web3";
// import { ensure } from "../../../utils/utils";

dotenv.config({path: ".env"});

async function runExample() {
// sender address
const fromAddress = '0x01234567890abcdef01234567890abcdef012345';
// recipient address
const toAddress = 'AbcDefGHIJklmNoPQRStuvwXyz1aBcDefG';

// configure web3
const web3 = new Web3('https://bsc-dataseed1.binance.org:443');
const account = web3.eth.accounts.privateKeyToAccount(process.env.PRIVATE_KEY);
web3.eth.accounts.wallet.add(account);

const sdk = new AllbridgeCoreSdk({
solanaRpcUrl: "your solana-rpc-url",
tronRpcUrl: "your tron-rpc-url",
});

// fetch information about supported chains
const chains = await sdk.chainDetailsMap();

const bscChain = chains[ChainSymbol.BSC];
const busdToken = bscChain.tokens.find(token => token.symbol === 'BUSD');

const trxChain = chains[ChainSymbol.TRX];
const usdtToken = trxChain.tokens.find(token => token.symbol === 'USDT');

// authorize a transfer of tokens from sender's address
await sdk.bridge.approve(web3, {
token: busdToken,
owner: fromAddress
});

// initiate transfer
const response = await sdk.bridge.send(web3, {
amount: "1.01",
fromAccountAddress: fromAddress,
toAccountAddress: toAddress,
sourceToken: busdToken,
destinationToken: usdtToken,
messenger: Messenger.ALLBRIDGE,
});
console.log("Tokens sent:", response.txId);
}
const fromAddress = getEnvVar("ETH_ACCOUNT_ADDRESS"); // sender address
const toAddress = getEnvVar("TRX_ACCOUNT_ADDRESS"); // recipient address

const sdk = new AllbridgeCoreSdk({ ...nodeRpcUrlsDefault, ETH: getEnvVar("WEB3_PROVIDER_URL") });

const chains = await sdk.chainDetailsMap();

const sourceChain = chains[ChainSymbol.ETH];
const sourceToken = ensure(sourceChain.tokens.find((tokenInfo) => tokenInfo.symbol === "USDC"));

const destinationChain = chains[ChainSymbol.POL];
const destinationToken = ensure(destinationChain.tokens.find((tokenInfo) => tokenInfo.symbol === "USDC"));

const amount = "1.01";

//check if sending tokens already approved
if (!(await sdk.bridge.checkAllowance({ token: sourceToken, owner: fromAddress, amount: amount }))) {
// authorize the bridge to transfer tokens from sender's address
const rawTransactionApprove = (await sdk.bridge.rawTxBuilder.approve({
token: sourceToken,
owner: fromAddress,
})) as RawEvmTransaction;
const approveTxReceipt = await sendEvmRawTransaction(rawTransactionApprove);
console.log("Approve tx id:", approveTxReceipt.transactionHash);
}

// initiate transfer
const rawTransactionTransfer = (await sdk.bridge.rawTxBuilder.send({
amount: amount,
fromAccountAddress: fromAddress,
toAccountAddress: toAddress,
sourceToken: sourceToken,
destinationToken: destinationToken,
messenger: Messenger.ALLBRIDGE,
})) as RawEvmTransaction;
console.log(`Sending ${amount} ${sourceToken.symbol}`);
const txReceipt = await sendEvmRawTransaction(rawTransactionTransfer);
console.log("tx id:", txReceipt.transactionHash);
}

runExample();
```
Expand All @@ -177,7 +190,8 @@ For more details, see [***Examples***](https://github.com/allbridge-io/allbridge
### Liquidity pools operations

SDK supports operation with **Liquidity Pools**<br/>
For more details, see [***Examples***](https://github.com/allbridge-io/allbridge-core-js-sdk/tree/main/examples/src/examples/liquidity-pool)
For more details, see [
***Examples***](https://github.com/allbridge-io/allbridge-core-js-sdk/tree/main/examples/src/examples/liquidity-pool)

### Transaction builder

Expand All @@ -186,28 +200,20 @@ For more details, see [***Examples***](https://github.com/allbridge-io/allbridge
SDK method `bridge.rawTxBuilder.approve` can be used to create approve Transaction.

```ts
const rawTransactionApprove = await sdk.bridge.rawTxBuilder.approve(provider, approveParams);
const rawTransactionApprove = await sdk.bridge.rawTxBuilder.approve(approveParams);
```

#### Send Transaction

SDK method `bridge.rawTxBuilder.send` can be used to create send Transaction.

```ts
const rawTransactionSend = await sdk.bridge.rawTxBuilder.send(sendParams, provider);
```

**TIP:** </br>
To interact with the **Solana** blockchain: </br>
do not pass provider param </p>

```ts
const transaction = await sdk.bridge.rawTxBuilder.send(sendParams);
const rawTransactionSend = await sdk.bridge.rawTxBuilder.send(sendParams);
```


***TIP:***
For more details, see [***Example***](https://github.com/allbridge-io/allbridge-core-js-sdk/blob/main/examples/src/examples/bridge/solana/sol-build-send-tx.js)
For more details, see [***Example
***](https://github.com/allbridge-io/allbridge-core-js-sdk/blob/main/examples/src/examples/bridge/solana/sol-build-send-tx.js)

### Get information about sent transaction

Expand Down Expand Up @@ -257,7 +263,7 @@ The method returns an object with two properties:
If this property is not present, it indicates that the stablecoin payment method is not available.

```ts
const { native, stablecoin } = await sdk.getGasFeeOptions(
const {native, stablecoin} = await sdk.getGasFeeOptions(
usdtOnEthToken, // from ETH
usdtOnTrxToken, // to TRX
Messenger.ALLBRIDGE
Expand Down
86 changes: 86 additions & 0 deletions documentation/browser/evm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@

# Integrating Allbridge Core SDK and Browser Extension Wallet with TypeScript

## Introduction
This documentation provides a step-by-step guide on integrating the Allbridge Core SDK and a browser extension wallet (MetaMask and WalletConnect) using TypeScript in a web project.

## Prerequisites
- TypeScript
- Node.js
- npm or yarn
- Allbridge Core SDK package installed ([`@allbridge/bridge-core-sdk`](https://www.npmjs.com/package/@allbridge/bridge-core-sdk))
- WalletConnect Provider (`@walletconnect/ethereum-provider`). [Docs](https://docs.walletconnect.com/)
- Web3.js library (`web3, web3-core`)
- MetaMask extension installed in the browser. [Docs](https://docs.metamask.io/)

## Installation
First, install the necessary packages:

```bash
npm install @allbridge/bridge-core-sdk @walletconnect/ethereum-provider web3
```

## Step-by-Step Integration

### Step 1: Import Necessary Modules

Import the required modules and initialize the Allbridge Core SDK:

```typescript
import {
AllbridgeCoreSdk,
NodeRpcUrls,
RawEvmTransaction,
SendParams,
} from '@allbridge/bridge-core-sdk';
import Web3 from 'web3';
import { AbstractProvider } from 'web3-core';
import EthereumProvider from '@walletconnect/ethereum-provider';
```

### Step 2: Define Node URLs and initialize SDK

Specifying nodes for EVM networks is optional, but can be done according to the `NodeRpcUrls` type:

```typescript
const SDK_NODE_URLS: NodeRpcUrls = {};
const sdk = new AllbridgeCoreSdk(SDK_NODE_URLS);
```

### Step 3: Define Web3

Define Web3 if you are using the MetaMask wallet:

```typescript
const web3: Web3 = new Web3(window.ethereum);
```

Define Web3 if you are using the WalletConnect protocol:

```typescript
const provider = await EthereumProvider.init({
projectId: 'YOUR_WALLET_CONNECT_PROJECT_ID',
methods: ['eth_sendTransaction'],
optionalChains: [chainId],
showQrModal: true,
});
await provider.enable();
const web3 = new Web3(provider as AbstractProvider);
```

### Step 4: Create, sign and send Allbridge raw transaction:

```typescript
const rawTransaction = (await sdk.bridge.rawTxBuilder.send(params)) as RawEvmTransaction;
const gasLimit = await web3.eth.estimateGas(rawTransaction);
const signedTx = await web3.eth.sendTransaction({
...rawTransaction,
gas: gasLimit,
});
const txId = signedTx.transactionHash;
console.log('txId', txId);
```

## Conclusion

With this guide, you have set up the Allbridge Core SDK and MetaMask wallet or WalletConnect protocol integration on your web application using TypeScript. You can now securely send transactions and check their status on the explorer. For further customization and advanced usage, refer to the official documentation of the respective SDKs.
Loading
Loading