Privatekey = wallet addres in flutter?

I need you to help me know if what I am doing is correct.

Future _login(
BuildContext context, WidgetRef ref, web3auth.Provider provider) async {
setState(() {
_isLoading = true;
});
try {
final Web3AuthResponse response = await Web3AuthFlutter.login(
LoginParams(loginProvider: provider),
);
await _handleLoginResponse(context, ref, response);
} catch (e) {
_handleLoginError(context, e);
} finally {
setState(() {
_isLoading = false;
});
}
}

Future _handleLoginResponse(
BuildContext context, WidgetRef ref, Web3AuthResponse response) async {
try {
final userInfo = await Web3AuthFlutter.getUserInfo();

  if (response.privKey != null) {
    await ref.read(sessionProvider.notifier).setSession(
          response.privKey!,
          userInfo,
        );

    final session = ref.read(sessionProvider);
    if (session != null && session.playerAddress.isNotEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text(
                'Login successful. Address: ${session.playerAddress}')),
      );

      // Delay navigation to ensure the user sees the wallet address
      await Future.delayed(Duration(seconds: 2));

      Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (context) => HomePage(
            privateKey: session.privateKey,
            userInfo: session.userInfo!,
            playerAddress: session.playerAddress,
          ),
        ),
      );
    } else {
      throw Exception('Failed to obtain player address');
    }
  } else {
    throw Exception('Private key is null');
  }
} catch (e) {
  print('Error in _handleLoginResponse: $e');
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text('Login failed: $e')),
  );
}

}

import ‘package:flutter_riverpod/flutter_riverpod.dart’;
import ‘package:shared_preferences/shared_preferences.dart’;
import ‘package:web3auth_flutter/output.dart’;
import ‘package:web3dart/web3dart.dart’;
import ‘dart:convert’;

class SessionModel {
final String privateKey;
final String playerAddress; // Changed from walletAddress to playerAddress
final TorusUserInfo? userInfo;
final String atonBalance;
final String ethBalance;

SessionModel({
required this.privateKey,
required this.playerAddress, // Changed from walletAddress to playerAddress
this.userInfo,
this.atonBalance = ‘0’,
this.ethBalance = ‘0’,
});

Map<String, dynamic> toJson() => {
‘privateKey’: privateKey,
‘playerAddress’:
playerAddress, // Changed from walletAddress to playerAddress
‘userInfo’: userInfo?.toJson(),
‘atonBalance’: atonBalance,
‘ethBalance’: ethBalance,
};

factory SessionModel.fromJson(Map<String, dynamic> json) => SessionModel(
privateKey: json[‘privateKey’],
playerAddress: json[
‘playerAddress’], // Changed from walletAddress to playerAddress
userInfo: json[‘userInfo’] != null
? TorusUserInfo.fromJson(json[‘userInfo’])
: null,
atonBalance: json[‘atonBalance’] ?? ‘0’,
ethBalance: json[‘ethBalance’] ?? ‘0’,
);
}

class SessionNotifier extends StateNotifier<SessionModel?> {
SessionNotifier() : super(null);

Future setSession(String privateKey, TorusUserInfo? userInfo) async {
final playerAddress = await _derivePlayerAddress(
privateKey); // Changed from _deriveWalletAddress to _derivePlayerAddress
final session = SessionModel(
privateKey: privateKey,
playerAddress:
playerAddress, // Changed from walletAddress to playerAddress
userInfo: userInfo,
);
state = session;
await _saveSession();
}

Future clearSession() async {
state = null;
await _clearSavedSession();
}

Future loadSession() async {
final prefs = await SharedPreferences.getInstance();
final sessionJson = prefs.getString(‘session’);
if (sessionJson != null) {
state = SessionModel.fromJson(Map<String, dynamic>.from(
json.decode(sessionJson) as Map,
));
}
}

Future updateBalances(String atonBalance, String ethBalance) async {
if (state != null) {
state = SessionModel(
privateKey: state!.privateKey,
playerAddress:
state!.playerAddress, // Changed from walletAddress to playerAddress
userInfo: state!.userInfo,
atonBalance: atonBalance,
ethBalance: ethBalance,
);
await _saveSession();
}
}

Future _derivePlayerAddress(String privateKey) async {
// Changed from _deriveWalletAddress to _derivePlayerAddress
final credentials = EthPrivateKey.fromHex(privateKey);
final address = await credentials.extractAddress();
return address.hexEip55;
}

Future _saveSession() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(‘session’, json.encode(state?.toJson()));
}

Future _clearSavedSession() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(‘session’);
}

String? get playerAddress =>
state?.playerAddress; // Changed from walletAddress to playerAddress
}

Hey, no the PrivateKey is not equivalent to the wallet address. Once you have the private key, you can use it to derive the KeyPair of Private Key and PubKey using web3dart package. Once you have installed the package, you can use the EthPrivateKey.fromHex function to derive the Credentials of Public Key, account address, and also use it sign the transaction.

Checkout details here: Integrate Web3Auth with the Ethereum Blockchain in Flutter | Web3Auth

I currently manage this, is correct?

Future _derivePlayerAddress(String privateKey) async {
final credentials = EthPrivateKey.fromHex(privateKey);
final address = await credentials.extractAddress();
return address.hexEip55;
}

Yes, this is the correct way

Currently I have an addres that I have and it is this one

0x50d15506d2bd57819557771132f89b9080650684

but in my application when I log in I still get this other one

0xD46Fb14cE503C9f163cA9C93873C40f49E38B580

why does this happen?

Can you please share the code snippets of how are you getting the both address, and what you are logging? This will help us to debug the issue.

this is my code with next js

initializeWeb3Auth: async () => {
try {
const privateKeyProvider = new EthereumPrivateKeyProvider({
config: { chainConfig: _chainConfig },
});
const web3auth = new Web3Auth({

    clientId,
    chainConfig: _chainConfig,
    privateKeyProvider,
    web3AuthNetwork: "sapphire_mainnet",
    uiConfig: {
      appName: "Arenaton",
      mode: "dark",
      // additional config
    },

  });

  // Set up adapters and plugins
  const metamaskAdapter = new MetamaskAdapter({
    clientId,
    chainConfig: _chainConfig,
  });
  const coinbaseAdapter = new CoinbaseAdapter({
    clientId,
    chainConfig: _chainConfig,
  });
  const walletServicesPlugin = new WalletServicesPlugin({
    walletInitOptions: { confirmationStrategy: "modal" },
  });

  web3auth.configureAdapter(metamaskAdapter);
  web3auth.configureAdapter(coinbaseAdapter);
  web3auth.addPlugin(walletServicesPlugin);

  await web3auth.initModal(); // Ensure modal is initialized

  set({
    web3auth,
    provider: web3auth.provider,
    isInitialized: true,
    walletServicesPlugin,
  });

  console.log("Web3Auth initialized for Arbitrum");
  await get().checkConnection();
} catch (error: any) {
  console.error("Error initializing Web3Auth:", error);
  set({
    error: "Failed to initialize Web3Auth. Please try again.",
  });
}

},

checkConnection: async () => {
const { web3auth } = get();
if (web3auth) {
const isConnected = await web3auth.connected;
console.log(“Checking connection:”, isConnected);
if (isConnected) {
const userInfo = await web3auth.getUserInfo();
const address = await web3auth.provider?.request({
method: “eth_accounts”,
});
console.log(“User info:”, userInfo);
console.log(“Address:”, address);
const playerAddress = Array.isArray(address) ? address[0] : null;
// const shortAddress = playerAddress
// ? ${playerAddress.slice(0, 4)}...${playerAddress.slice(-4)}
// : “Not connected”;
set({
connected: true,
playerAddress,
profileImage: userInfo.profileImage || null, // Add this line
});
await get().fetchPlayerSummary();
} else {
const defaultAddress = “0x0000000000000000000000220000000000000001”;
set({
connected: false,
playerAddress: defaultAddress,
});
await get().fetchPlayerSummary();
}
}
}

login: async () => {
const { web3auth } = get();
if (!web3auth) {
console.error(“Web3Auth not initialized”);
set({
error:
“Web3Auth not initialized. Please refresh the page and try again.”,
});
return;
}
try {
console.log(“Attempting to connect…”);
const web3authProvider = await web3auth.connect();
console.log(“Connected successfully”);
set({ provider: web3authProvider });
await get().checkConnection();
} catch (error: any) {
console.error(“Error during login:”, error);
}
}

this is my flutter code

Future initPlatformState() async {
final themeMap = HashMap<String, String>();
themeMap[‘primary’] = “#fff000”;

Uri redirectUrl;
if (Platform.isAndroid) {
  redirectUrl = Uri.parse(
      'torusapp://org.torusresearch.flutter.web3authexample/auth');
} else if (Platform.isIOS) {
  redirectUrl =
      Uri.parse('torusapp://org.torusresearch.flutter.web3authexample');
} else {
  throw Exception('Unsupported platform');
}

await Web3AuthFlutter.init(
  Web3AuthOptions(
    clientId: Config.clientId,
    network: Network.sapphire_devnet,
    redirectUrl: redirectUrl,
    whiteLabel: WhiteLabelData(
      mode: ThemeModes.dark,
      appName: "Arenaton< Flutter App",
      theme: themeMap,
    ),
  ),
);

await Web3AuthFlutter.initialize();

}

Future _login(
BuildContext context, WidgetRef ref, web3auth.Provider provider) async {
setState(() {
_isLoading = true;
});
try {
final Web3AuthResponse response = await Web3AuthFlutter.login(
LoginParams(loginProvider: provider),
);
await _handleLoginResponse(context, ref, response);
} catch (e) {
_handleLoginError(context, e);
} finally {
setState(() {
_isLoading = false;
});
}
}

Future _handleLoginResponse(
BuildContext context, WidgetRef ref, Web3AuthResponse response) async {
try {
final userInfo = await Web3AuthFlutter.getUserInfo();

  if (response.privKey != null) {
    await ref.read(sessionProvider.notifier).setSession(
          response.privKey!,
          userInfo,
        );

    final session = ref.read(sessionProvider);
    if (session != null && session.walletAddress.isNotEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text(
                'Login successful. Address: ${session.walletAddress}')),
      );

      // Delay navigation to ensure the user sees the wallet address
      await Future.delayed(Duration(seconds: 2));

      Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (context) => HomePage(
            privateKey: session.privateKey,
            userInfo: session.userInfo!,
            walletAddress: session.walletAddress,
          ),
        ),
      );
    } else {
      throw Exception('Failed to obtain wallet address');
    }
  } else {
    throw Exception('Private key is null');
  }
} catch (e) {
  print('Error in _handleLoginResponse: $e');
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text('Login failed: $e')),
  );
}

}

void _handleLoginError(BuildContext context, dynamic error) {
print(error);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(‘Login failed: $error’)),
);
}

Do you mean to say the address you are getting on the next js and Flutter are not same? You are using the different networks hence the address is not same. On Next jS your Web3AuthNetwork is Sapphire Mainnet, but on Flutter it’s Sapphire Devnet. Please Sapphire Mainnet on Flutter.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.