Skip to content

Instantly share code, notes, and snippets.

@quetool
Created April 22, 2024 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quetool/60be285159dbef65685b1ddac296ed2f to your computer and use it in GitHub Desktop.
Save quetool/60be285159dbef65685b1ddac296ed2f to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:web3modal_flutter/web3modal_flutter.dart';
import 'package:walletconnect_flutter_v2/apis/sign_api/utils/custom_credentials.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late W3MService _w3mService;
@override
void initState() {
super.initState();
_initWalletService();
}
void _initWalletService() async {
// Sepolia has to be added in the chain lists so it can be approved
W3MChainPresets.chains.putIfAbsent(_sepolia.chainId, () => _sepolia);
_w3mService = W3MService(
projectId: '....',
metadata: const PairingMetadata(
name: '....',
description: '....',
url: 'https://..../',
icons: [],
redirect: Redirect(
native: '....://',
universal: 'https://..../',
),
),
);
_w3mService.onModalConnect.subscribe(_onModalConnect);
_w3mService.onModalDisconnect.subscribe(_onModalDisconnect);
await _w3mService.init();
setState(() {});
}
void _onModalConnect(ModalConnect? event) async {
debugPrint('_onModalConnect($event)');
setState(() {});
}
void _onModalDisconnect(ModalDisconnect? event) {
debugPrint('_onModalDisconnect($event)');
setState(() {});
}
Future<void> _callWriteFunction() async {
final abi = await rootBundle.loadString('....abi.json');
const contractAddress = '0x52....';
_w3mService.launchConnectedWallet();
try {
final deployedContract = DeployedContract(
ContractAbi.fromJson(abi, '....'),
EthereumAddress.fromHex(contractAddress),
);
await requestWriteContract(
topic: _w3mService.session?.topic ?? '',
chainId: 'eip155:11155111',
rpcUrl: 'https://ethereum-sepolia.publicnode.com',
deployedContract: deployedContract,
functionName: 'subscribe',
parameters: [],
transaction: Transaction(
from: EthereumAddress.fromHex(_w3mService.session!.address!),
value: EtherAmount.fromInt(EtherUnit.finney, 1),
),
);
} catch (e, s) {
debugPrint('Error calling write function: $e, $s');
}
}
Future<dynamic> requestWriteContract({
required String topic,
required String chainId,
required String rpcUrl,
required DeployedContract deployedContract,
required String functionName,
required Transaction transaction,
String? method,
List<dynamic> parameters = const [],
}) async {
final credentials = CustomCredentials(
signEngine: _w3mService.web3App!.signEngine,
topic: topic,
chainId: chainId,
address: transaction.from!,
method: method,
);
final trx = Transaction.callContract(
contract: deployedContract,
function: deployedContract.function(functionName),
from: credentials.address,
value: transaction.value,
parameters: parameters,
);
if (chainId.contains(':')) {
chainId = chainId.split(':').last;
}
return await Web3Client(rpcUrl, http.Client()).sendTransaction(
credentials,
trx,
chainId: int.parse(chainId),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: ElevatedButton(
onPressed: _w3mService.isConnected
? () {
_callWriteFunction();
}
: null,
child: const Text('Call Write Function'),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
_w3mService.openModal(context);
},
child: Icon(
_w3mService.isConnected
? Icons.link_outlined
: Icons.link_off_outlined,
size: 30.0,
),
),
);
}
}
final _sepolia = W3MChainInfo(
chainName: 'Sepolia Testnet',
chainId: '11155111',
namespace: 'eip155:11155111',
tokenName: 'SEP',
rpcUrl: 'https://eth-sepolia.g.alchemy.com/v2/kgakyspjgeajykfh',
blockExplorer: W3MBlockExplorer(
name: 'Sepolia Etherscan',
url: 'https://sepolia.etherscan.io/',
),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment