Skip to content

Commit

Permalink
add emulateAccount fn (#1157)
Browse files Browse the repository at this point in the history
  • Loading branch information
lowkeynicc authored Aug 22, 2024
1 parent bab0d6f commit 1ff2c34
Showing 1 changed file with 48 additions and 3 deletions.
51 changes: 48 additions & 3 deletions sdk/src/driftClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,51 @@ export class DriftClient {
return success;
}

/**
* Update the subscribed accounts to a given authority, while leaving the
* connected wallet intact. This allows a user to emulate another user's
* account on the UI and sign permissionless transactions with their own wallet.
* @param emulateAuthority
*/
public async emulateAccount(emulateAuthority: PublicKey): Promise<boolean> {
this.skipLoadUsers = false;
// Update provider for txSender with new wallet details
this.authority = emulateAuthority;
this.userStatsAccountPublicKey = undefined;
this.includeDelegates = true;
const walletSupportsVersionedTxns =
//@ts-ignore
this.wallet.supportedTransactionVersions?.size ?? 0 > 1;
this.txVersion = walletSupportsVersionedTxns ? 0 : 'legacy';

this.authoritySubAccountMap = new Map<string, number[]>();

/* Reset user stats account */
if (this.userStats?.isSubscribed) {
await this.userStats.unsubscribe();
}

this.userStats = undefined;

this.userStats = new UserStats({
driftClient: this,
userStatsAccountPublicKey: this.getUserStatsAccountPublicKey(),
accountSubscription: this.userStatsAccountSubscriptionConfig,
});

await this.userStats.subscribe();

let success = true;

if (this.isSubscribed) {
await Promise.all(this.unsubscribeUsers());
this.users.clear();
success = await this.addAndSubscribeToUsers(emulateAuthority);
}

return success;
}

public async switchActiveUser(subAccountId: number, authority?: PublicKey) {
const authorityChanged = authority && !this.authority?.equals(authority);

Expand Down Expand Up @@ -771,7 +816,7 @@ export class DriftClient {
/**
* Adds and subscribes to users based on params set by the constructor or by updateWallet.
*/
public async addAndSubscribeToUsers(): Promise<boolean> {
public async addAndSubscribeToUsers(authority?: PublicKey): Promise<boolean> {
// save the rpc calls if driftclient is initialized without a real wallet
if (this.skipLoadUsers) return true;

Expand Down Expand Up @@ -799,12 +844,12 @@ export class DriftClient {
let delegatedAccounts = [];

const userAccountsPromise = this.getUserAccountsForAuthority(
this.wallet.publicKey
authority ?? this.wallet.publicKey
);

if (this.includeDelegates) {
const delegatedAccountsPromise = this.getUserAccountsForDelegate(
this.wallet.publicKey
authority ?? this.wallet.publicKey
);
[userAccounts, delegatedAccounts] = await Promise.all([
userAccountsPromise,
Expand Down

0 comments on commit 1ff2c34

Please sign in to comment.