Skip to content

Commit

Permalink
add connection store
Browse files Browse the repository at this point in the history
  • Loading branch information
zlayine committed Oct 12, 2023
1 parent c348315 commit e45f008
Show file tree
Hide file tree
Showing 7 changed files with 209 additions and 177 deletions.
14 changes: 7 additions & 7 deletions resources/js/components/SignTransaction.vue
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
</div>
<div v-else-if="!loadingApi && !signing" class="flex flex-col space-y-2 animate-fade-in">
<div
v-for="account in useAppStore().accounts"
v-for="account in connectionStore.accounts"
:key="account.address"
class="px-4 py-3 border border-gray-300 rounded-md cursor-pointer hover:bg-primary/20 transition-all flex items-center space-x-4"
@click="selectAccount(account)"
Expand All @@ -34,7 +34,7 @@
</span>
</div>
</div>
<div v-if="!useAppStore().accounts?.length" class="text-center">
<div v-if="!connectionStore.accounts?.length" class="text-center">
<span class="text-sm text-gray-500"> No accounts found. Please connect your wallet. </span>
</div>
</div>
Expand All @@ -51,13 +51,13 @@ import { DialogTitle } from '@headlessui/vue';
import Btn from './Btn.vue';
import Modal from './Modal.vue';
import { addressShortHex } from '~/util/address';
import { useAppStore } from '~/store';
import { useTransactionStore } from '~/store/transaction';
import { ref } from 'vue';
import LoadingCircle from './LoadingCircle.vue';
import snackbar from '~/util/snackbar';
import Identicon from './Identicon.vue';
import { formatPriceFromENJ } from '~/util';
import { useConnectionStore } from '~/store/connection';
const props = defineProps<{
transaction: any;
Expand All @@ -71,19 +71,19 @@ const feeCost = ref();
const loadingApi = ref(false);
const signing = ref(false);
const appStore = useAppStore();
const transactionStore = useTransactionStore();
const connectionStore = useConnectionStore();
const signTransaction = async () => {
try {
if (!appStore.provider) {
if (!connectionStore.provider) {
snackbar.error({ title: 'Please connect your wallet to sign' });
return;
}
showAccountsModal.value = true;
loadingApi.value = true;
appStore.getAccounts();
connectionStore.getAccounts();
await transactionStore.init();
feeCost.value = formatPriceFromENJ(props.transaction.fee)?.toFixed(5);
loadingApi.value = false;
Expand All @@ -100,7 +100,7 @@ const closeModal = () => {
const selectAccount = async (account) => {
try {
isLoading.value = true;
await appStore.setAccount(account);
await connectionStore.setAccount(account);
signing.value = true;
const res = await transactionStore.signTransaction(props.transaction);
if (res) {
Expand Down
12 changes: 6 additions & 6 deletions resources/js/components/WalletConnectButton.vue
Original file line number Diff line number Diff line change
Expand Up @@ -57,25 +57,25 @@

<script setup lang="ts">
import { WalletIcon } from '@heroicons/vue/24/outline';
import { useAppStore } from '~/store';
import LoadingCircle from './LoadingCircle.vue';
import { computed, ref } from 'vue';
import { Menu, MenuButton, MenuItem, MenuItems } from '@headlessui/vue';
import ScaleTransition from './ScaleTransition.vue';
import snackbar from '~/util/snackbar';
import { useConnectionStore } from '~/store/connection';
const appStore = useAppStore();
const connectionStore = useConnectionStore();
const loading = ref(false);
const showAccountsModal = ref(false);
const walletSession = computed(() => appStore.wallet);
const walletSession = computed(() => connectionStore.wallet);
const connectWallet = async (provider: string) => {
try {
loading.value = true;
await appStore.connectWallet(provider);
if (appStore.accounts) {
await connectionStore.connectWallet(provider);
if (connectionStore.accounts) {
showAccountsModal.value = true;
}
} catch {
Expand All @@ -87,7 +87,7 @@ const connectWallet = async (provider: string) => {
const disconnectWallet = async () => {
loading.value = true;
await appStore.disconnectWallet();
await connectionStore.disconnectWallet();
loading.value = false;
};
</script>
171 changes: 171 additions & 0 deletions resources/js/store/connection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { defineStore } from 'pinia';
import { ConnectionState } from '~/types/types.interface';
import { wcOptions } from '~/util';
import { wcRequiredNamespaces } from '~/util';
import { getAppMetadata, getSdkError } from '@walletconnect/utils';
import { PolkadotjsWallet, Wallet } from '@talismn/connect-wallets';
import SignClient from '@walletconnect/sign-client';
import { HexString } from '@polkadot/util/types';
import { wcNamespaces, wcProjectId } from '~/util/constants';
import { useAppStore } from '.';
import { WalletConnectModalSign } from '@walletconnect/modal-sign-html';

export const useConnectionStore = defineStore('connection', {
state: (): ConnectionState => ({
provider: '',
wallet: false,
walletClient: null,
walletSession: null,
account: null,
accounts: null,
}),
persist: {
paths: ['provider'],
},
actions: {
getWeb3Modal() {
return new WalletConnectModalSign(wcOptions);
},
async connectWallet(provider) {
if (provider === 'wc') {
await this.connectWC();
}

if (provider === 'polkadot.js') {
await this.connectPolkadotJS();
}
},
async initWalletClient() {
this.walletClient = await SignClient.init({
projectId: wcProjectId,
metadata: getAppMetadata(),
});

if (this.walletClient) {
this.walletClient.on('session_delete', () => {
this.disconnectWallet();
});
this.walletClient.on('session_expire', () => {
this.disconnectWallet();
});
}

this.walletClient.session.getAll({});
if (this.walletClient.session.length) {
const lastKeyIndex = this.walletClient.session.keys.length - 1;
this.walletSession = this.walletClient.session.get(this.walletClient.session.keys[lastKeyIndex]);
}
},
async connectWC() {
const walletConnect = this.getWeb3Modal();
await this.initWalletClient();

this.walletSession = await walletConnect.connect({
requiredNamespaces: wcRequiredNamespaces(useAppStore().config.network),
});

if (this.walletSession && this.walletSession.acknowledged) {
this.provider = 'wc';
this.wallet = true;
await this.initWalletClient();

return;
}

await walletConnect!.disconnect({
topic: this.walletSession.topic,
reason: getSdkError('USER_REJECTED'),
});

this.account = null;
},
async connectPolkadotJS() {
const pkjs = new PolkadotjsWallet();
if (pkjs.installed) {
await pkjs.enable('Platform');
this.wallet = true;
this.provider = 'polkadot.js';
this.walletSession = pkjs;
}
},

async getSession(): Promise<any> {
if (this.provider === 'wc') {
await this.initWalletClient();

if (this.walletSession?.acknowledged) {
this.wallet = true;
}
} else if (this.provider === 'polkadot.js') {
const pkjs = new PolkadotjsWallet();
this.walletSession = pkjs;

if (this.walletSession.installed) {
await this.walletSession.enable('Platform');
this.wallet = true;
}
}
return this.walletSession;
},
async disconnectWallet() {
try {
if (this.provider === 'wc') {
if (this.walletClient) {
this.walletClient.disconnect({
topic: this.walletSession.topic,
reason: getSdkError('USER_DISCONNECTED'),
});
}
}
} finally {
this.account = null;
this.wallet = false;
this.provider = '';
this.walletClient = null;
this.walletSession = null;
}
},
async setAccount(account: Wallet) {
if (this.provider === 'wc') {
account.signer = {
signPayload: async (payload: any) => {
const result = await (this.walletClient! as SignClient).request<{ signature: HexString }>({
chainId: wcNamespaces[useAppStore().config.network],
topic: this.walletSession?.topic,
request: {
method: 'polkadot_signTransaction',
params: {
address: payload.address,
transactionPayload: payload,
},
},
});

return result;
},
};
}
this.account = account;
},
async getAccounts() {
if (this.provider === 'wc') {
if (!this.walletSession) {
return;
}

const accounts = Object.values(this.walletSession.namespaces)
.map((namespace: any) => namespace.accounts)
.flat()
.map((account) => {
return {
address: account.split(':')[2],
};
});
this.accounts = accounts;
} else if (this.provider === 'polkadot.js') {
const accounts = await this.walletSession.getAccounts();
this.accounts = accounts;
}
},
},
});
Loading

0 comments on commit e45f008

Please sign in to comment.