Skip to content

Commit

Permalink
feat(sdk): add getNativeTokenBalance
Browse files Browse the repository at this point in the history
  • Loading branch information
AntonKozAllB committed Nov 17, 2023
1 parent f3100c6 commit b1c7021
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 25 deletions.
40 changes: 17 additions & 23 deletions examples/src/examples/bridge/send-by-cctp.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
import {
AllbridgeCoreSdk,
ChainSymbol,
Messenger,
nodeRpcUrlsDefault,
SendParams,
} from "@allbridge/bridge-core-sdk";
import {TransactionConfig} from "web3-core";
import { AllbridgeCoreSdk, ChainSymbol, Messenger, nodeRpcUrlsDefault, SendParams } from "@allbridge/bridge-core-sdk";
import { TransactionConfig } from "web3-core";
import Web3 from "web3";
import {sendRawTransaction} from "../../utils/web3";
import {ensure} from "../../utils/utils";
import {getEnvVar} from "../../utils/env";
import { sendRawTransaction } from "../../utils/web3";
import { ensure } from "../../utils/utils";
import { getEnvVar } from "../../utils/env";

const ETH_NODE_RPC_URL = getEnvVar("ETH_NODE_RPC_URL");
const privateKey = getEnvVar("ETH_PRIVATE_KEY");
Expand All @@ -23,11 +17,11 @@ web3.eth.accounts.wallet.add(account);
const main = async () => {
const sdk = new AllbridgeCoreSdk({
...nodeRpcUrlsDefault,
ETH: ETH_NODE_RPC_URL
ETH: ETH_NODE_RPC_URL,
});
const chainDetailsMap = await sdk.chainDetailsMap();
const sourceToken = ensure(chainDetailsMap[ChainSymbol.ETH].tokens.find(t => t.symbol == "USDC"));
const destinationToken = ensure(chainDetailsMap[ChainSymbol.ARB].tokens.find(t => t.symbol == "USDC"));
const sourceToken = ensure(chainDetailsMap[ChainSymbol.ETH].tokens.find((t) => t.symbol == "USDC"));
const destinationToken = ensure(chainDetailsMap[ChainSymbol.ARB].tokens.find((t) => t.symbol == "USDC"));
//check if tokens support cctp
if (sourceToken.cctpAddress && destinationToken.cctpAddress) {
//send by cctp
Expand All @@ -36,29 +30,29 @@ const main = async () => {
amount,
token: sourceToken,
owner: fromAccountAddress,
messenger: Messenger.CCTP
})
console.log("checkAllowance", checkAllowance)
messenger: Messenger.CCTP,
});
console.log("checkAllowance", checkAllowance);
if (checkAllowance == false) {
const approveParams = {
token: sourceToken,
owner: fromAccountAddress,
messenger: Messenger.CCTP
}
messenger: Messenger.CCTP,
};
const tx = await sdk.bridge.rawTxBuilder.approve(approveParams);
const txReceipt = await sendRawTransaction(web3, tx as TransactionConfig);
console.log("approve tx id:", txReceipt.transactionHash);
}
const willBeReceived = await sdk.getAmountToBeReceived(amount, destinationToken, sourceToken, Messenger.CCTP);
console.log("willBeReceived", willBeReceived)
console.log("willBeReceived", willBeReceived);
const sendParams: SendParams = {
amount,
fromAccountAddress,
toAccountAddress,
destinationToken,
sourceToken,
messenger: Messenger.CCTP
}
messenger: Messenger.CCTP,
};
const tx = await sdk.bridge.rawTxBuilder.send(sendParams);
//sign and send raw Tx
const txReceipt = await sendRawTransaction(web3, tx as TransactionConfig);
Expand All @@ -72,4 +66,4 @@ main()
})
.catch((e) => {
console.error(e);
});
});
11 changes: 11 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
Messenger,
} from "./models";
import { BridgeService, DefaultBridgeService } from "./services/bridge";
import { GetNativeTokenBalanceParams } from "./services/bridge/models";
import { SolanaBridgeParams } from "./services/bridge/sol";
import { getExtraGasMaxLimits, getGasFeeOptions } from "./services/bridge/utils";
import { DefaultLiquidityPoolService, LiquidityPoolService } from "./services/liquidity-pool";
Expand Down Expand Up @@ -184,6 +185,16 @@ export class AllbridgeCoreSdk {
return this.tokenService.getTokenBalance(params, provider);
}

/**
* Get native (gas) token balance
* @param params
* @param provider
* @returns Token balance
*/
async getNativeTokenBalance(params: GetNativeTokenBalanceParams, provider?: Provider): Promise<AmountFormatted> {
return this.tokenService.getNativeTokenBalance(params, provider);
}

/**
* @Deprecated
* Calculates the percentage of fee from the initial amount that is charged when swapping from the selected source chain.
Expand Down
8 changes: 8 additions & 0 deletions src/services/bridge/models/bridge.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ export interface GetTokenBalanceParams {
token: TokenWithChainDetails;
}

export interface GetNativeTokenBalanceParams {
/**
* The address for which we will find out the token balance
*/
account: string;
chainSymbol: ChainSymbol;
}

export interface BaseSendParams {
/**
* The float amount of Total tokens to transfer.
Expand Down
5 changes: 5 additions & 0 deletions src/services/token/evm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { AbiItem } from "web3-utils";
import { ChainSymbol, ChainType } from "../../../chains";
import { AllbridgeCoreClient } from "../../../client/core-api";
import { GetTokenBalanceParams, TransactionResponse } from "../../../models";
import { GetNativeTokenBalanceParams } from "../../bridge/models";
import { RawTransaction } from "../../models";
import { BaseContract } from "../../models/abi/types/types";
import { amountToHex } from "../../utils/index";
Expand Down Expand Up @@ -42,6 +43,10 @@ export class EvmTokenService extends ChainTokenService {
.call();
}

async getNativeTokenBalance(params: GetNativeTokenBalanceParams): Promise<string> {
return await this.web3.eth.getBalance(params.account);
}

async approve(params: ApproveParamsDto): Promise<TransactionResponse> {
if (this.isUsdt(params.tokenAddress)) {
const allowance = await this.getAllowanceByTokenAddress(params.tokenAddress, params.owner, params.spender);
Expand Down
22 changes: 20 additions & 2 deletions src/services/token/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import { Big } from "big.js";
// @ts-expect-error import tron
import TronWeb from "tronweb";
import Web3 from "web3";
import { chainProperties, ChainSymbol, ChainType } from "../../chains";
import { ChainDecimalsByType, chainProperties, ChainSymbol, ChainType } from "../../chains";
import { AllbridgeCoreClient } from "../../client/core-api";
import { MethodNotSupportedError, NodeRpcUrlsConfig } from "../../index";
import { AmountFormat, AmountFormatted, MethodNotSupportedError, NodeRpcUrlsConfig } from "../../index";
import { validateAmountDecimals, validateAmountGtZero } from "../../utils";
import { convertFloatAmountToInt, convertIntAmountToFloat } from "../../utils/calculation";
import { GetNativeTokenBalanceParams } from "../bridge/models";
import { Provider, RawTransaction, TransactionResponse } from "../models";
import { EvmTokenService } from "./evm";
import {
Expand All @@ -31,6 +32,8 @@ export interface TokenService {
buildRawTransactionApprove(approveData: ApproveParams, provider?: Provider): Promise<RawTransaction>;

getTokenBalance(params: GetTokenBalanceParams, provider?: Provider): Promise<string>;

getNativeTokenBalance(params: GetNativeTokenBalanceParams, provider?: Provider): Promise<AmountFormatted>;
}

export class DefaultTokenService implements TokenService {
Expand Down Expand Up @@ -85,6 +88,21 @@ export class DefaultTokenService implements TokenService {
return tokenBalance;
}

async getNativeTokenBalance(params: GetNativeTokenBalanceParams, provider?: Provider): Promise<AmountFormatted> {
const tokenBalance = await this.getChainTokenService(
params.chainSymbol,
params.account,
provider
).getNativeTokenBalance(params);
return {
[AmountFormat.INT]: tokenBalance,
[AmountFormat.FLOAT]: convertIntAmountToFloat(
tokenBalance,
ChainDecimalsByType[chainProperties[params.chainSymbol].chainType]
).toFixed(),
};
}

private getChainTokenService(chainSymbol: ChainSymbol, ownerAddress: string, provider?: Provider): ChainTokenService {
switch (chainProperties[chainSymbol].chainType) {
case ChainType.EVM: {
Expand Down
3 changes: 3 additions & 0 deletions src/services/token/models/token.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Big } from "big.js";
import { ChainType } from "../../../chains";
import { AllbridgeCoreClient } from "../../../client/core-api";
import { GetNativeTokenBalanceParams } from "../../bridge/models";
import { RawTransaction, TransactionResponse } from "../../models";
import { ApproveParamsDto, CheckAllowanceParamsDto, GetAllowanceParamsDto, GetTokenBalanceParams } from "./token.model";

Expand All @@ -10,6 +11,8 @@ export abstract class ChainTokenService {

abstract getTokenBalance(params: GetTokenBalanceParams): Promise<string>;

abstract getNativeTokenBalance(params: GetNativeTokenBalanceParams): Promise<string>;

abstract getAllowance(params: GetAllowanceParamsDto): Promise<string>;

async checkAllowance(params: CheckAllowanceParamsDto): Promise<boolean> {
Expand Down
7 changes: 7 additions & 0 deletions src/services/token/sol/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Connection, PublicKey } from "@solana/web3.js";
import { ChainType } from "../../../chains";
import { AllbridgeCoreClient } from "../../../client/core-api";
import { MethodNotSupportedError } from "../../../exceptions";
import { GetNativeTokenBalanceParams } from "../../bridge/models";
import { RawTransaction, TransactionResponse } from "../../models";
import { getTokenAccountData } from "../../utils/sol";
import { getAssociatedAccount } from "../../utils/sol/accounts";
Expand Down Expand Up @@ -60,4 +61,10 @@ export class SolanaTokenService extends ChainTokenService {
throw e;
}
}

async getNativeTokenBalance(params: GetNativeTokenBalanceParams): Promise<string> {
return (
await this.buildAnchorProvider(params.account).connection.getBalance(new PublicKey(params.account))
).toString();
}
}
5 changes: 5 additions & 0 deletions src/services/token/trx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ChainType } from "../../../chains";
import { AllbridgeCoreClient } from "../../../client/core-api";
import { SdkError } from "../../../exceptions";
import { GetTokenBalanceParams, TransactionResponse } from "../../../models";
import { GetNativeTokenBalanceParams } from "../../bridge/models";
import { RawTransaction, SmartContractMethodParameter } from "../../models";
import { amountToHex } from "../../utils";
import { sendRawTransaction } from "../../utils/trx";
Expand Down Expand Up @@ -36,6 +37,10 @@ export class TronTokenService extends ChainTokenService {
return balance.toString();
}

async getNativeTokenBalance(params: GetNativeTokenBalanceParams): Promise<string> {
return (await this.tronWeb.trx.getBalance(params.account)).toString();
}

async approve(params: ApproveParamsDto): Promise<TransactionResponse> {
const rawTransaction = await this.buildRawTransactionApprove(params);
return await sendRawTransaction(this.tronWeb, rawTransaction);
Expand Down

0 comments on commit b1c7021

Please sign in to comment.