Dapp connect to wallets

Aptos Web3

Hello guys!

I’m Pierre from Fewcha wallet. After developing Fewcha for two months, we realized the need to create a library for integrating and connecting Dapps and Wallets.

Based on the idea of web3 connections, So I created @fewcha/web3 and @fewcha/web3-react.

Our web3 lib now supports standard implemented wallets discussed here: Wallet dApp API Standards (Aptos Official Wallet, Fewcha, Martian)

You can learn more about how to use it at @fewcha/web3 - npm.

Implement at UI

If you are using React, you should use the @fewcha/web3-react for easy integration and get realtime state updates.

Install @fewcha/web3-react

yarn add aptos @fewcha/web3 @fewcha/web3-react

Here is example:

import React from "react";
import Web3Provider from "@fewcha/web3-react";

const App: React.FC = () => {
  return (
    <Web3Provider>
      {/* your website */}
    </Web3Provider>
  );
};

export default App;
import { useWeb3 } from "@fewcha/web3-react";

// in your React component:

const web3 = useWeb3();
const { init, account, balance, isConnected, connect, disconnect, network, txs, sdk, token } = web3;

/*
init: boolean - for check web3 is ready yet

account: PublicAccount - wallet address, "" if not connected yet
balance: string - wallet balance

isConnected: boolean - check the website is connected yet (realtime)
connect: function - trigger connect popup
disconnect: function - trigger disconnect action

network: string - current Node URL

txs: array of transactions created in this session

sdk: Aptos SDK functions
token: Aptos TokenClient functions

...
*/

And transaction functions can get from web3:

  • generateTransaction(payload: TransactionPayload, options?: Partial<UserTransactionRequest>): Promise<UserTransactionRequest>;
  • signAndSubmitTransaction(txnRequest: UserTransactionRequest): Promise<PendingTransaction>;
  • signTransaction(txnRequest: UserTransactionRequest): Promise<SubmitTransactionRequest>;
  • signMessage(message: string): Promise<string>;
  • submitTransaction(signedTxnRequest: SubmitTransactionRequest): Promise<PendingTransaction>;
  • simulateTransaction(txnRequest: UserTransactionRequest): Promise<OnChainTransaction>;
  • generateBCSTransaction(rawTxn: TxnBuilderTypes.RawTransaction): Uint8Array;
  • generateBCSSimulation(rawTxn: TxnBuilderTypes.RawTransaction): Uint8Array;
  • submitSignedBCSTransaction(signedTxn: Uint8Array): Promise<PendingTransaction>;
  • submitBCSSimulation(bcsBody: Uint8Array): Promise<OnChainTransaction>;

for the above Typescript types, can use direct types from Aptos SDK:

import { TxnBuilderTypes } from "aptos";
import { TransactionPayload, UserTransactionRequest, SubmitTransactionRequest, PendingTransaction, OnChainTransaction } from "aptos/dist/api/data-contracts";
import { PublicAccount } from "@fewcha/web3/dist/types";

Basic auth flow example

import { useWeb3 } from "@fewcha/web3-react";

// in your react component
const web3 = useWeb3();
  const { init, account, balance, isConnected, connect, disconnect, network, txs, sdk, token } = web3;

// in your header
<div>
  <div>
    {isConnected ? (
      <div>
        <div>Address: {account.address}</div>
        <div>Balance: {balance}</div>
        <div>Network: {network}</div>
        <div>
          <button
            onClick={() => {
              disconnect();
            }}
          >
            Disconnect
          </button>
        </div>
      </div>
    ) : (
      <div>
        <button
          onClick={() => {
            connect();
          }}
        >
          Connect
        </button>
      </div>
    )}
  </div>
</div>

For CRA example, please check at https://github.com/fewcha-wallet/aptos-web3/tree/main/packages/cra-web3-react.

For the Nextjs example, please check at aptos-web3/packages/nextjs-web3-react at main · fewcha-wallet/aptos-web3 · GitHub.

(All functions will work from Wallet prototype version 0.3.4: Release v0.3.4 · fewcha-wallet/dev-versions · GitHub)

Support multiple wallets

Note: @fewcha/web3 now supports all wallets that follow the standard, @fewcha/web3-react currently only supports Fewcha; we will support all wallets and provide a React popup component so your users can choose the wallet they want as soon as possible. Stay tuned to this thread. It should be:

import { ConnectWallet } from "@fewcha/web3-react";

// in your header

<ConnectWallet />
<ConnectWallet type="grid" /> // type is optional, default is list

Est: @fewcha/web3-react version 0.2.0 (~ July 18) will support it

The APIs

And standards, API functions, etc… you can use with the lib (Fewcha Wallet prototype 0.3.4 will support all of it):

export type PublicAccount = {
  address: string;
  publicKey: string;
};

export interface Web3ProviderType {
  connect(): Promise<PublicAccount>;
  disconnect(): Promise<void>;
  isConnected(): Promise<boolean>;

  generateTransaction(payload: TransactionPayload, options?: Partial<UserTransactionRequest>): Promise<UserTransactionRequest>;

  signAndSubmitTransaction(txnRequest: UserTransactionRequest): Promise<PendingTransaction>;
  signTransaction(txnRequest: UserTransactionRequest): Promise<SubmitTransactionRequest>;
  signMessage(message: string): Promise<string>;
  submitTransaction(signedTxnRequest: SubmitTransactionRequest): Promise<PendingTransaction>;

  simulateTransaction(txnRequest: UserTransactionRequest): Promise<OnChainTransaction>;

  generateBCSTransaction(rawTxn: TxnBuilderTypes.RawTransaction): Uint8Array;
  generateBCSSimulation(rawTxn: TxnBuilderTypes.RawTransaction): Uint8Array;

  submitSignedBCSTransaction(signedTxn: Uint8Array): Promise<PendingTransaction>;
  submitBCSSimulation(bcsBody: Uint8Array): Promise<OnChainTransaction>;

  account(): Promise<PublicAccount>;
  getNodeURL(): Promise<string>;
  getBalance(): Promise<string>;

  sdk: {
    getAccount(accountAddress: MaybeHexString): Promise<Account>;
    getAccountTransactions(accountAddress: MaybeHexString, query?: { start?: number; limit?: number }): Promise<OnChainTransaction[]>;
    getAccountModules(accountAddress: MaybeHexString, query?: { version?: LedgerVersion }): Promise<MoveModule[]>;
    getAccountModule(accountAddress: MaybeHexString, moduleName: string, query?: { version?: LedgerVersion }): Promise<MoveModule>;
    getAccountResources(accountAddress: MaybeHexString, query?: { version?: LedgerVersion }): Promise<AccountResource[]>;
    getAccountResource(accountAddress: MaybeHexString, resourceType: string, query?: { version?: LedgerVersion }): Promise<AccountResource>;

    getEventsByEventKey(eventKey: HexEncodedBytes): Promise<Event[]>;
    getEventsByEventHandle(address: MaybeHexString, eventHandleStruct: MoveStructTagId, fieldName: string, query?: { start?: number; limit?: number }): Promise<Event[]>;

    getTransactions(query?: { start?: number; limit?: number }): Promise<OnChainTransaction[]>;
    getTransaction(txnHashOrVersion: string): Promise<Transaction>;

    transactionPending(txnHash: HexEncodedBytes): Promise<boolean>;
    waitForTransaction(txnHash: HexEncodedBytes): Promise<void>;
    getLedgerInfo(params: RequestParams): Promise<LedgerInfo>;
    getChainId(params: RequestParams): Promise<number>;
    getTableItem(handle: string, data: TableItemRequest, params?: RequestParams): Promise<any>;
  };

  token: {
    createCollection(name: string, description: string, uri: string): Promise<string>;
    createToken(collectionName: string, name: string, description: string, supply: number, uri: string, royalty_points_per_million: number): Promise<string>;
    offerToken(receiver: MaybeHexString, creator: MaybeHexString, collectionName: string, name: string, amount: number): Promise<HexEncodedBytes>;
    claimToken(sender: MaybeHexString, creator: MaybeHexString, collectionName: string, name: string): Promise<HexEncodedBytes>;
    cancelTokenOffer(receiver: MaybeHexString, creator: MaybeHexString, collectionName: string, name: string): Promise<HexEncodedBytes>;

    getCollectionData(creator: MaybeHexString, collectionName: string): Promise<any>;
    getTokenData(creator: MaybeHexString, collectionName: string, tokenName: string): Promise<TokenData>;
    getTokenBalance(creator: MaybeHexString, collectionName: string, tokenName: string): Promise<Token>;
    getTokenBalanceForAccount(account: MaybeHexString, tokenId: TokenId): Promise<Token>;
  };
}

from aptos-web3/types.ts at main · fewcha-wallet/aptos-web3 · GitHub

Support

We are happy to support you in integrating it on your dapp.

Please feel free to contact us on Discord: Fewcha - Aptos Wallet.
Or ping me directly at Telegram: Telegram: Contact @pierreneter.

For business matters, please ping Telegram: Contact @SIP_Gab.

10 Likes

Connect Fewcha Wallet with @fewcha/web3-react. How smooth is it?

Switch account

Please support us by following: https://twitter.com/fewchawallet

We just released Wallet dev-version 0.3.5 Release v0.3.5 · fewcha-wallet/dev-versions · GitHub

You can try Wallet Selector from now, @fewcha/web3-react version v0.1.1 https://www.npmjs.com/package/@fewcha/web3-react

Easy to use:

import Web3Provider from "@fewcha/web3-react";
<Web3Provider>{/* your app */}</Web3Provider>

Your app header

import { ConnectWallet, useWeb3 } from "@fewcha/web3-react";

const web3 = useWeb3();
  const { account, balance, isConnected, disconnect, network, txs, sdk, token } = web3;

  return (
    <div>
      <div>
        {isConnected ? (
          <div>
            <div>Address: {account.address}</div>
            <div>Balance: {balance || "0"}</div>
            <div>Network: {network}</div>
            <div>
              <button
                onClick={() => {
                  disconnect();
                }}
              >
                Disconnect
              </button>
            </div>
          </div>
        ) : (
          <ConnectWallet type="list" />
        )}
      </div>
    </div>
  );

At your components

const web3 = useWeb3();
const { sdk, token,  generateTransaction,  signAndSubmitTransaction, simulateTransaction } = web3;

Example transaction

// get estimate gas for send balance and call
const receiverAddress = "0x788b3f37e8925b444fafa49becee9bd4489b1ef1a4005fdd6eac47e4e6d71531";
const sendBalance = "1000";
const payload = {
 type: "script_function_payload",
 function: "0x1::Coin::transfer",
 type_arguments: ["0x1::TestCoin::TestCoin"],
 arguments: [receiverAddress, sendBalance],
};
const txnRequest = await generateTransaction(payload);
const transactionEstRes = await simulateTransaction(txnRequest);
if (transactionEstRes.success) {
 console.log(transactionEstRes.gas_used);
} else {
 console.error(transactionEstRes.vm_status);
}
const transactionRes = await signAndSubmitTransaction(txnRequest);
console.log(transactionRes.hash);
await sdk.waitForTransaction(transactionRes.hash);
const tx = await sdk.getTransaction(transactionRes.hash);
console.log(tx.success);
1 Like

We can edit connect button style and popup style in next release