1.2.6 • Published 1 month ago

@cxptek/web3client v1.2.6

Weekly downloads
-
License
MIT
Repository
-
Last release
1 month ago

About web3client

npm

The web3client package provides a web3 clients that facilitates interaction with various wallets and blockchain networks, including Metamask, TronLink. It provides functionalities for working with Ethereum and Tron.

Usage

Here's a basic example of how to instantiate and use the web3client package:

Import web3client in your code:
import { Web3Service, MetaMaskClient, TronLinkClient, bsc, bscTestnet, nile, tron } from '@cxptek/web3client';
Create a Web3Service instance

You can use a Metamask or Tron client. As an example using Metamask:

//Metamask
const supportedChains = [bsc, bscTestnet, nile, tron];
const metamaskClient = new MetaMaskClient({ chains: supportedChains });
const web3Service = new Web3Service(metamaskClient);

//TronLink
const tronClient = new TronLinkClient({ chains: supportedChains });
const _web3Service = new Web3Service(tronClient);

Methods web3Client offers

Connect Mumbai to MetaMask
 import { ChainsMap } from "@cxptek/web3client";

 const mumbaiChain = ChainsMap.get(80_001);
 const connectResponse = await web3Service.client.connect(mumbaiChain)
Switch chain to Ethereum
 const ethereumChain = ChainsMap.get(1);
 const connectResponse = await web3Service.client.switchChain (ethereumChain);
Sign a message
 const signature = await web3Service.client.signMessage("Message to sign");
Send raw transaction
 import { BigNumber, utils } from 'ethers';
 import { type EthereumTransaction } from '@cxptek/web3client';

 const tx: EthereumTransaction = {
     nonce: 1,
     chainId: 1,
     data: '0x',
     gasLimit: BigNumber.from(600_000),
     from: "0x95222290dd7278aa3ddd389cc1e1d165cc4bafe5",
     to: '0x91da5bf3F8Eb72724E6f50Ec6C3D199C6355c59c',
     value: utils.parseUnits('0.0001', 18),
   };

   const response = await web3Service.client.sendRawTransaction(tx);
Sign transaction
import { BigNumber, utils } from 'ethers';
import { type EthereumTransaction } from 'web3client';

const tx: EthereumTransaction = {
  nonce: 1,
  chainId: 1,
  data: '',
  gasLimit: BigNumber.from(600_000),
  to: address,
  value: '1',
};

await web3Service.client.signTransaction(tx);
Send native token
 const response = await web3Service.client.send(address, '0.0001');

 const receiptConfirmed = await response.wait(1);
Is Installed or is Unlocked
 const isInstalled = web3Service.client.isInstalled();
Is Unlocked
 const isUnlocked = await web3Service.client.isUnlocked();
Authenticate User using their wallet and an specific API
 import { AuthenticateWalletWithAPI} from "web3client";

 const client = new Metamask()
 await client.authenticateWalletWithAPI(aPIUrl).then((e) => {
     console.log('AuthenticateWalletWithAPI', e)
   }).catch(error => {
     console.log('Error', error)
   })
Change Web3 language

The web3 library is using lingui as localization library to provide messages and translations in many languages. The app language can be changed using the method: activateLanguage('en-US')

 After any label or text that should be translated, you should do:
 yarn extract (this will create the new keys)
 yarn compile (This command compiles message catalogs in localeDir and outputs minified Javascript files)
getAllowance

Returns the token spend allowed by an address on behalf of the crypto holder

const spenderAddress = '0x123..8099'; // liquidity pool address
const tokenAddress = '0x456...789'; // USDT token address
const account = '0x121...999'; // my address
let allowance = await client.getAllowance(account, spenderAddress, tokenAddress, 18);
console.log('allowance in decimal', allowance);
approveToken

Before other smart contract can use your assets, you must approve amount of assets. Just call this method:

const spenderAddress = '0x123..8099'; // liquidity pool address
const tokenAddress = '0x456...789'; // USDT token address
const amount = 10; // 10 USDT in decimal.
await _web3Service.client.approve(spenderAddress, tokenAddress, amount, 18);
Execute native smart contract methods (Write methods)

We can use this method to call any write method from smart contract.

const writeContract = (
  address: string, // smart contract address | token address
  abi: ContractInterface, // ABI encode
  method: string, // name of smart contract method.
  params: Record<string, any>, // smart contract method arguments
  options?: Record<string, any> // other options such as Gas limit on metamask.
) => Promise<any>;

// Execute swap method from liquidity pool
const swapAmount = parseUnits(10, 18); // 18 for bsc
const swapResponse = await _web3Service.client.writeContract(
  address,
  ABI_DATA,
  'swap',
  { amount: swapAmount, recipient: '0x12333545' },
  { gasLimit: 800000 }
);

Web3 Events

accountsChanged

Listen whenever user change his account

web3Service.client.on('accountsChanged', (accounts: string[]) => {
  console.log('Account Changed', accounts);
});
chainChanged

Listen whenever user change network

web3Service.client.on('chainChanged', (newChain: { id: number; isUnsupported: boolean }) => {
  console.log('chain Changed', newChain);
  // {id: number, isUnsupported: boolean}
});
disconnect

Listen whenever user has disconnected

web3Service.client.on('disconnect', () => {
  console.log('disconnected');
});
removeAllListeners
web3Service.client.removeAllListeners();

Supported Chains

  • Ethereum
    • Ethereum (1)
    • Goerli ()
    • Polygon (137)
    • Mumbai (80001)
    • Binance smart chain (56)
    • Binance smart chain testnet (97)
  • Tron
    • Tron grid
    • Nile
1.2.6

1 month ago

1.2.5

1 month ago

1.2.4

1 month ago

1.2.3

1 month ago

1.2.2

1 month ago

1.2.1

1 month ago

1.2.0

1 month ago

1.1.9

2 months ago

1.1.8

2 months ago

1.1.7

2 months ago

1.1.6

2 months ago

1.1.5

2 months ago

1.1.4

3 months ago

1.1.2

3 months ago

1.1.1

3 months ago

1.1.0

4 months ago

1.0.8

5 months ago

1.0.7

5 months ago

1.0.6

5 months ago

1.0.5

5 months ago

1.0.4

5 months ago

1.0.3

5 months ago

1.0.2

6 months ago

1.0.1

7 months ago

1.0.0

7 months ago