Skip to content

Commit

Permalink
Supporting the new SDK with wallet adapter (#193)
Browse files Browse the repository at this point in the history
* Initial commit of working on v2 wallet adapter

Consolidating things and removing comments

Updating package.json and removing unnecessary imports

* Move signAndSubmitBCSTransaction back up

* Adding updated types to make wallet adapter work

* Remove old TypeTagParser

* Update documentation to clarify v2 sdk

* Remove signAnyTransaction for now

* Updating documentation/comments

* Remove unused functions

* Add account undefined check

* Updating @aptos-labs/ts-sdk version and changing new TypeTagParser to parseTypeTag()

* Make submitTransaction return { hash: string, output?: any }

Make submitTransaction return { hash: string, output?: any }

* Using BCS arguments instead of simple ones

* Rebasing and updating pnpm-lock.yaml

* Removing extraneous package

* Adding changeset
  • Loading branch information
xbtmatt authored Nov 1, 2023
1 parent fca59e8 commit 7acfa69
Show file tree
Hide file tree
Showing 11 changed files with 3,448 additions and 2,985 deletions.
7 changes: 7 additions & 0 deletions .changeset/mighty-peas-sniff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@aptos-labs/wallet-adapter-react": minor
"@aptos-labs/wallet-adapter-core": minor
"@aptos-labs/wallet-adapter-nextjs-example": minor
---

Adding support for the new Typescript SDK in the package `@aptos-labs/ts-sdk`. The wallet adapter now supports submitting a basic transaction with the new SDK types.
1 change: 1 addition & 0 deletions apps/nextjs-example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"@welldone-studio/aptos-wallet-adapter": "^0.1.4",
"antd": "^5.1.2",
"aptos": "^1.19.0",
"@aptos-labs/ts-sdk": "^0.0.3",
"ethers": "^5.7.2",
"fewcha-plugin-wallet-adapter": "^0.1.3",
"next": "13.0.0",
Expand Down
25 changes: 25 additions & 0 deletions apps/nextjs-example/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
APTOS_COIN,
AptosAccount,
AptosClient,
BCS,
Expand All @@ -9,6 +10,7 @@ import {
TxnBuilderTypes,
Types
} from "aptos";
import { AccountAddress, U64, parseTypeTag } from "@aptos-labs/ts-sdk";
import {NetworkName, useWallet} from "@aptos-labs/wallet-adapter-react";
import {WalletConnector} from "@aptos-labs/wallet-adapter-mui-design";
import dynamic from "next/dynamic";
Expand Down Expand Up @@ -317,6 +319,7 @@ function OptionalFunctionality() {
signTransaction,
signMessageAndVerify,
signMultiAgentTransaction,
submitTransaction,
} = useWallet();
let sendable = isSendableNetwork(connected, network?.name)

Expand Down Expand Up @@ -467,6 +470,26 @@ function OptionalFunctionality() {
);
};

const onSubmitTransaction = async () => {
if(!account){
throw new Error("Account not connected");
}
const response = await submitTransaction({
sender: account.address,
data: {
function: "0x1::coin::transfer",
typeArguments: [parseTypeTag(APTOS_COIN)],
functionArguments: [AccountAddress.fromHexInputRelaxed(account.address), new U64(1)], // 1 is in Octas
}
});
try {
await aptosClient(network?.name.toLowerCase()).waitForTransaction(response.hash);
setSuccessAlertHash(response.hash, network?.name);
} catch (error) {
console.error(error);
}
};

return <Row>
<Col title={true} border={true}>
<h3>Optional Feature Functions</h3>
Expand All @@ -479,6 +502,8 @@ function OptionalFunctionality() {
message={"Sign and submit BCS transaction"}/>
<Button color={"blue"} onClick={onSubmitFeePayer} disabled={!sendable}
message={"Sign and submit fee payer"}/>
<Button color={"blue"} onClick={onSubmitTransaction} disabled={!sendable}
message={"Sign and submit with the @aptos-labs/ts-sdk"}/>
</Col>
</Row>;
}
Expand Down
1 change: 1 addition & 0 deletions packages/wallet-adapter-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"typescript": "^4.5.3"
},
"dependencies": {
"@aptos-labs/ts-sdk": "^0.0.3",
"buffer": "^6.0.3",
"eventemitter3": "^4.0.7",
"tweetnacl": "^1.0.3"
Expand Down
68 changes: 47 additions & 21 deletions packages/wallet-adapter-core/src/WalletCore.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {HexString, TxnBuilderTypes, Types} from "aptos";
import { HexString, TxnBuilderTypes, Types } from "aptos";
import { AptosConfig, InputGenerateTransactionData, generateTransactionPayload } from "@aptos-labs/ts-sdk";
import EventEmitter from "eventemitter3";
import nacl from "tweetnacl";
import { Buffer } from "buffer";
Expand Down Expand Up @@ -38,6 +39,8 @@ import {
isRedirectable,
} from "./utils";
import { getNameByAddress } from "./ans";
import { AccountAuthenticator } from "@aptos-labs/ts-sdk";
import { convertNetwork, convertToBCSPayload } from "./conversion";

export class WalletCore extends EventEmitter<WalletCoreEvents> {
private _wallets: ReadonlyArray<Wallet> = [];
Expand Down Expand Up @@ -289,12 +292,12 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
}

/**
Sign and submit a bsc serialized transaction type to chain.
@param transaction a bcs serialized transaction
@param options max_gas_amount and gas_unit_limit
@return response from the wallet's signAndSubmitBCSTransaction function
@throws WalletSignAndSubmitMessageError
*/
Sign and submit a bsc serialized transaction type to chain.
@param transaction a bcs serialized transaction
@param options max_gas_amount and gas_unit_limit
@return response from the wallet's signAndSubmitBCSTransaction function
@throws WalletSignAndSubmitMessageError
*/
async signAndSubmitBCSTransaction(
transaction: TxnBuilderTypes.TransactionPayload,
options?: TransactionOptions
Expand All @@ -320,12 +323,12 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
}

/**
Sign transaction (doesnt submit to chain).
@param transaction
@param options max_gas_amount and gas_unit_limit
@return response from the wallet's signTransaction function
@throws WalletSignTransactionError
*/
Sign transaction (doesnt submit to chain).
@param transaction
@param options max_gas_amount and gas_unit_limit
@return response from the wallet's signTransaction function
@throws WalletSignTransactionError
*/
async signTransaction(
transaction: Types.TransactionPayload,
options?: TransactionOptions
Expand All @@ -351,11 +354,11 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
}

/**
Sign message (doesnt submit to chain).
@param message
@return response from the wallet's signMessage function
@throws WalletSignMessageError
*/
Sign message (doesnt submit to chain).
@param message
@return response from the wallet's signMessage function
@throws WalletSignMessageError
*/
async signMessage(
message: SignMessagePayload
): Promise<SignMessageResponse | null> {
Expand All @@ -371,23 +374,46 @@ export class WalletCore extends EventEmitter<WalletCoreEvents> {
}
}

/**
* This function is for signing and submitting a transaction using the `@aptos-labs/ts-sdk` (aka the v2 SDK)
* input types. It's internally converting the input types to the old SDK input types and then calling
* the v1 SDK's `signAndSubmitBCSTransaction` with it.
*
* @param transactionInput the transaction input
* @param options max_gas_amount and gas_unit_limit
* @returns the response from the wallet's signAndSubmitBCSTransaction function
*/
async submitTransaction(
transactionInput: InputGenerateTransactionData,
options?: TransactionOptions,
): Promise<{ hash: string, output?: any }> {
const payloadData = transactionInput.data;
const aptosConfig = new AptosConfig({network: convertNetwork(this._network)});
// TODO: Refactor this any, and remove the need for it by fixing the if ("bytecode" in data) stuff in `generateTransaction` in the v2 SDK
const newPayload = await generateTransactionPayload({ ...payloadData as any, aptosConfig: aptosConfig });
const oldTransactionPayload = convertToBCSPayload(newPayload);
const response = await this.signAndSubmitBCSTransaction(oldTransactionPayload, options);
const { hash, ...output } = response;
return { hash, output };
}

async signMultiAgentTransaction(
transaction: TxnBuilderTypes.MultiAgentRawTransaction | TxnBuilderTypes.FeePayerRawTransaction
): Promise<string | null> {
if (this._wallet && !("signMultiAgentTransaction" in this._wallet)) {
throw new WalletNotSupportedMethod(
`Multi agent & Fee payer transactions are not supported by ${this.wallet?.name}`
`Multi-agent & sponsored transactions are not supported by ${this.wallet?.name}`
).message;
}
try {
this.doesWalletExist();
const response = await (this._wallet as any).signMultiAgentTransaction(
transaction
transaction
);
return response;
} catch (error: any) {
const errMsg =
typeof error == "object" && "message" in error ? error.message : error;
typeof error == "object" && "message" in error ? error.message : error;
throw new WalletSignTransactionError(errMsg).message;
}
}
Expand Down
24 changes: 24 additions & 0 deletions packages/wallet-adapter-core/src/conversion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Network, AnyTransactionPayloadInstance } from "@aptos-labs/ts-sdk"
import { BCS, TxnBuilderTypes } from "aptos"
import { NetworkInfo } from "./types";
import { NetworkName } from "./constants";

// old => new
export function convertNetwork(networkInfo: NetworkInfo | null): Network {
switch(networkInfo?.name.toLowerCase()) {
case "mainnet" as NetworkName:
return Network.MAINNET;
case "testnet" as NetworkName:
return Network.TESTNET;
case "devnet" as NetworkName:
return Network.DEVNET;
default:
throw new Error("Invalid network name")
}
}

// new => old
export function convertToBCSPayload(payload: AnyTransactionPayloadInstance): TxnBuilderTypes.TransactionPayload {
const deserializer = new BCS.Deserializer(payload.bcsToBytes());
return TxnBuilderTypes.TransactionPayload.deserialize(deserializer);
}
1 change: 1 addition & 0 deletions packages/wallet-adapter-core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { TxnBuilderTypes, Types } from "aptos";
import { NetworkName, WalletReadyState } from "./constants";

export { TxnBuilderTypes, Types } from "aptos";
export type { InputGenerateTransactionData } from "@aptos-labs/ts-sdk";
// WalletName is a nominal type that wallet adapters should use, e.g. `'MyCryptoWallet' as WalletName<'MyCryptoWallet'>`
export type WalletName<T extends string = string> = T & {
__brand__: "WalletName";
Expand Down
2 changes: 1 addition & 1 deletion packages/wallet-adapter-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
"tsup": "^5.10.1"
},
"dependencies": {
"@aptos-labs/wallet-adapter-core": "^2.5.2"
"@aptos-labs/wallet-adapter-core": "workspace:*"
},
"peerDependencies": {
"react": "^18"
Expand Down
15 changes: 14 additions & 1 deletion packages/wallet-adapter-react/src/WalletProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type {
TransactionOptions,
TxnBuilderTypes,
Types,
InputGenerateTransactionData,
} from "@aptos-labs/wallet-adapter-core";
import { WalletCore } from "@aptos-labs/wallet-adapter-core";

Expand Down Expand Up @@ -134,7 +135,6 @@ export const AptosWalletAdapterProvider: FC<AptosWalletProviderProps> = ({
}
};


const signMultiAgentTransaction = async (
transaction: TxnBuilderTypes.MultiAgentRawTransaction | TxnBuilderTypes.FeePayerRawTransaction,
) => {
Expand All @@ -147,6 +147,18 @@ export const AptosWalletAdapterProvider: FC<AptosWalletProviderProps> = ({
}
}

const submitTransaction = async (
transaction: InputGenerateTransactionData,
) => {
try {
return await walletCore.submitTransaction(transaction);
} catch (error: any) {
if (onError) onError(error);
else throw error;
return false;
}
}

useEffect(() => {
if (autoConnect) {
if (localStorage.getItem("AptosWalletName")) {
Expand Down Expand Up @@ -254,6 +266,7 @@ export const AptosWalletAdapterProvider: FC<AptosWalletProviderProps> = ({
signMessage,
signMessageAndVerify,
signMultiAgentTransaction,
submitTransaction,
isLoading,
}}
>
Expand Down
3 changes: 2 additions & 1 deletion packages/wallet-adapter-react/src/useWallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
TransactionOptions,
TxnBuilderTypes,
Types,
InputGenerateTransactionData,
} from "@aptos-labs/wallet-adapter-core";
import { createContext, useContext } from "react";

Expand Down Expand Up @@ -49,7 +50,7 @@ export interface WalletContextState {
): Promise<any>;
signMessage(message: SignMessagePayload): Promise<SignMessageResponse | null>;
signMessageAndVerify(message: SignMessagePayload): Promise<boolean>;

submitTransaction(transaction: InputGenerateTransactionData): Promise<any>;
signMultiAgentTransaction(
transaction: TxnBuilderTypes.MultiAgentRawTransaction | TxnBuilderTypes.FeePayerRawTransaction,
): Promise<any>;
Expand Down
Loading

0 comments on commit 7acfa69

Please sign in to comment.