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

allow wallet connect to connect with solana chains #1956

Merged
merged 5 commits into from
Sep 24, 2024
Merged
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 .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ jobs:
cd demo/vue-app-new
npm install
npm run build
env:
env:
VITE_SOLANA_MAINNET_RPC: ${{ secrets.VITE_SOLANA_MAINNET_RPC }}
VITE_APP_PIMLICO_API_KEY: ${{ secrets.PIMLICO_API_KEY }}

# Copy the files from build folder to the S3 bucket
Expand Down
1 change: 1 addition & 0 deletions demo/vue-app-new/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# VITE_SOLANA_MAINNET_RPC="enter your rpc endpoint here"
51 changes: 48 additions & 3 deletions demo/vue-app-new/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions demo/vue-app-new/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,14 @@
"@web3auth/torus-solana-adapter": "file:../../packages/adapters/torus-solana-adapter",
"@web3auth/wallet-connect-v2-adapter": "file:../../packages/adapters/wallet-connect-v2-adapter",
"@web3auth/wallet-services-plugin": "file:../../packages/plugins/wallet-services-plugin",
"bs58": "^5.0.0",
"ethers": "^6.13.2",
"vue": "^3.4.31",
"vue-i18n": "^9.13.1"
},
"devDependencies": {
"@toruslabs/eslint-config-vue": "^3.3.1",
"@types/bs58": "^4.0.4",
"@vitejs/plugin-vue": "^5.0.5",
"autoprefixer": "^10.4.19",
"eslint": "^8.54.0",
Expand Down
104 changes: 84 additions & 20 deletions demo/vue-app-new/src/components/AppDashboard.vue
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
<script setup lang="ts">
import { METHOD_TYPES } from "@toruslabs/ethereum-controllers";
import { Button, Card } from "@toruslabs/vue-components";
import { CHAIN_NAMESPACES, IProvider, WALLET_ADAPTERS, WALLET_PLUGINS } from "@web3auth/base";
import { CHAIN_NAMESPACES, IProvider, log, WALLET_ADAPTERS, WALLET_PLUGINS } from "@web3auth/base";
import { useWeb3Auth } from "@web3auth/modal-vue-composables";
import { WalletServicesPlugin } from "@web3auth/wallet-services-plugin";
import { recoverAddress, TypedDataEncoder, verifyMessage } from "ethers";
import { useI18n } from "vue-i18n";

import {
getAccounts,
getBalance,
getChainId,
sendEth,
signEthMessage,
signPersonalMessage,
signTransaction,
signTypedMessage,
} from "../services/ethHandlers";
import { signAllTransactions, signAndSendTransaction, signMessage } from "../services/solHandlers";
import { getV4TypedData } from "../config";
import { getAccounts, getBalance, getChainId, sendEth, signEthMessage, signTransaction as signEthTransaction } from "../services/ethHandlers";
import { signAllTransactions, signAndSendTransaction, signMessage, signTransaction as signSolTransaction } from "../services/solHandlers";
import { formDataStore } from "../store/form";

const { t } = useI18n({ useScope: "global" });
const { log } = console;

const formData = formDataStore;

Expand Down Expand Up @@ -117,7 +110,7 @@ const onGetBalance = async () => {
};

const onSwitchChain = async () => {
log("switching chain");
log.info("switching chain");
try {
await switchChain({ chainId: "0x89" });
printToConsole("switchedChain");
Expand Down Expand Up @@ -147,8 +140,12 @@ const onSignAndSendTransaction = async () => {
await signAndSendTransaction(provider.value as IProvider, printToConsole);
};

const onSignTransaction = async () => {
await signTransaction(provider.value as IProvider, printToConsole);
const onSignEthTransaction = async () => {
await signEthTransaction(provider.value as IProvider, printToConsole);
};

const onSignSolTransaction = async () => {
await signSolTransaction(provider.value as IProvider, printToConsole);
};

const onSignMessage = async () => {
Expand All @@ -159,12 +156,77 @@ const onSignAllTransactions = async () => {
await signAllTransactions(provider.value as IProvider, printToConsole);
};

const authenticateUser = async () => {
try {
const idToken = await web3Auth.value?.authenticateUser();
printToConsole("idToken", idToken);
} catch (error) {
log.error("authenticateUser error", error);
printToConsole("authenticateUser error", error);
}
};

const onSignTypedData_v4 = async () => {
await signTypedMessage(provider.value as IProvider, printToConsole);
try {
printToConsole("Initiating sign typed data v4");

const chain = await getChainId(provider.value as IProvider, () => {});
const accounts = await getAccounts(provider.value as IProvider, () => {});
const typedData = getV4TypedData(chain as string);
let signTypedDataV4VerifyResult = "";
// const signedMessage = await ethersProvider?.send("eth_signTypedData_v4", [account.value, JSON.stringify(typedData)]);

const from = accounts?.[0];

const signedMessage = (await provider.value?.request({
method: METHOD_TYPES.ETH_SIGN_TYPED_DATA_V4,
params: [from, JSON.stringify(typedData)],
})) as string;

const msg = TypedDataEncoder.hash(typedData.domain, typedData.types, typedData.message);
const recoveredAddr = recoverAddress(msg, signedMessage);
if (recoveredAddr.toLowerCase() === from?.toLowerCase()) {
log.info(`Successfully verified signer as ${recoveredAddr}`);
signTypedDataV4VerifyResult = recoveredAddr;
} else {
throw new Error(`Failed to verify signer when comparing ${recoveredAddr} to ${from}`);
}
printToConsole(`Success`, { signedMessage, verify: signTypedDataV4VerifyResult });
} catch (error) {
log.error(error);
printToConsole("Failed", (error as Error).message);
}
};

const onSignPersonalMsg = async () => {
await signPersonalMessage(provider.value as IProvider, printToConsole);
try {
printToConsole("Initiating personal sign");
const message = "Example `personal_sign` messages";
const accounts = await getAccounts(provider.value as IProvider, () => {});
const from = accounts?.[0];
let personalSignVerifySigUtilResult = "";
// const signedMessage = await ethersProvider?.send("personal_sign", [message, account.value]);
const msg = `0x${Buffer.from(message, "utf8").toString("hex")}`;
const signedMessage = (await provider.value?.request({
method: METHOD_TYPES.PERSONAL_SIGN,
params: [msg, from, "Example password"],
})) as string;

// Verify
const recoveredAddr = verifyMessage(message, signedMessage);

if (recoveredAddr.toLowerCase() === from?.toLowerCase()) {
log.info(`SigUtil Successfully verified signer as ${recoveredAddr}`);
personalSignVerifySigUtilResult = recoveredAddr;
} else {
throw new Error(`SigUtil Failed to verify signer when comparing ${recoveredAddr} to ${from}`);
}

printToConsole(`Success`, { signedMessage, verify: personalSignVerifySigUtilResult });
} catch (error) {
log.error(error);
printToConsole("Failed", (error as Error).message);
}
};
</script>

Expand Down Expand Up @@ -203,7 +265,7 @@ const onSignPersonalMsg = async () => {
{{ t("app.buttons.btnGetBalance") }}
</Button>
<Button block size="xs" pill class="mb-2" @click="onSendEth">{{ t("app.buttons.btnSendEth") }}</Button>
<Button block size="xs" pill class="mb-2" @click="onSignTransaction">
<Button block size="xs" pill class="mb-2" @click="onSignEthTransaction">
{{ t("app.buttons.btnSignTransaction") }}
</Button>
<Button block size="xs" pill class="mb-2" @click="onSignEthMessage">{{ t("app.buttons.btnSignEthMessage") }}</Button>
Expand All @@ -216,6 +278,7 @@ const onSignPersonalMsg = async () => {
<Button block size="xs" pill class="mb-2" @click="onSignPersonalMsg">
{{ t("app.buttons.btnSignPersonalMsg") }}
</Button>
<Button block size="xs" pill class="mb-2" @click="authenticateUser">Get id token</Button>
</Card>
<Card v-if="isDisplay('solServices')" class="h-auto gap-4 px-4 py-4 mb-2" :shadow="false">
<div class="mb-2 text-xl font-bold leading-tight text-left">Sample Transaction</div>
Expand All @@ -224,13 +287,14 @@ const onSignPersonalMsg = async () => {
<Button block size="xs" pill class="mb-2" @click="onSignAndSendTransaction">
{{ t("app.buttons.btnSignAndSendTransaction") }}
</Button>
<Button block size="xs" pill class="mb-2" @click="onSignTransaction">
<Button block size="xs" pill class="mb-2" @click="onSignSolTransaction">
{{ t("app.buttons.btnSignTransaction") }}
</Button>
<Button block size="xs" pill class="mb-2" @click="onSignMessage">{{ t("app.buttons.btnSignMessage") }}</Button>
<Button block size="xs" pill class="mb-2" @click="onSignAllTransactions">
{{ t("app.buttons.btnSignAllTransactions") }}
</Button>
<Button block size="xs" pill class="mb-2" @click="authenticateUser">Get id token</Button>
</Card>
</Card>
<Card
Expand Down
1 change: 1 addition & 0 deletions demo/vue-app-new/src/components/AppSettings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const adapterOptions = computed(() =>
]
: [
{ name: "torus-solana-adapter", value: "torus-solana" },
{ name: "wallet-connect-v2-adapter", value: "wallet-connect-v2" },
{ name: "injected-adapters", value: "injected-solana" },
]
);
Expand Down
12 changes: 11 additions & 1 deletion demo/vue-app-new/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,24 @@ export const chainConfigs: Record<ChainNamespaceType, CustomChainConfig[]> = {
},
],
[CHAIN_NAMESPACES.SOLANA]: [
// Ref: https://namespaces.chainagnostic.org/solana/caip10
{
chainNamespace: CHAIN_NAMESPACES.SOLANA,
rpcTarget: "https://api.devnet.solana.com",
blockExplorerUrl: "https://solscan.io",
logo: "https://cryptologos.cc/logos/solana-sol-logo.png",
chainId: "0x3",
ticker: "SOL",
tickerName: "Solana",
tickerName: "Solana Devnet",
},
{
chainNamespace: CHAIN_NAMESPACES.SOLANA,
rpcTarget: import.meta.env.VITE_SOLANA_MAINNET_RPC,
blockExplorerUrl: "https://explorer.solana.com",
logo: "https://cryptologos.cc/logos/solana-sol-logo.png",
chainId: "0x1",
ticker: "SOL",
tickerName: "Solana Mainnet",
},
],
[CHAIN_NAMESPACES.CASPER]: [],
Expand Down
8 changes: 5 additions & 3 deletions demo/vue-app-new/src/services/solHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { Connection, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction } from "@solana/web3.js";
import { CustomChainConfig, IProvider, log } from "@web3auth/base";
import { SolanaWallet } from "@web3auth/solana-provider";
import base58 from "bs58";

const getConnection = async (provider: IProvider): Promise<Connection> => {
const solanaWallet = new SolanaWallet(provider);
Expand Down Expand Up @@ -77,6 +78,7 @@ export const signTransaction = async (provider: IProvider, uiConsole: any) => {
const conn = await getConnection(provider);
const solWeb3 = new SolanaWallet(provider);
const pubKey = await solWeb3.requestAccounts();
log.info("pubKey", pubKey);

const block = await conn.getLatestBlockhash("finalized");
const transactionInstruction = SystemProgram.transfer({
Expand All @@ -92,8 +94,7 @@ export const signTransaction = async (provider: IProvider, uiConsole: any) => {
}).add(transactionInstruction);

const signedTx = await solWeb3.signTransaction(transaction);

// const res = await conn.sendRawTransaction(signedTx.serialize());
log.info("signedTx", signedTx);
uiConsole("signature", signedTx);
return { signature: signedTx };
} catch (error) {
Expand All @@ -108,7 +109,8 @@ export const signMessage = async (provider: IProvider, uiConsole: any) => {
const solWeb3 = new SolanaWallet(provider);
const msg = Buffer.from("Test Signing Message ", "utf8");
const res = await solWeb3.signMessage(new Uint8Array(msg));
uiConsole(res);
const parsedResult = base58.encode(res);
uiConsole("solana signed message", parsedResult);
} catch (error) {
log.error("Error", error);
uiConsole("error", error);
Expand Down
Loading