Skip to main content

near_wallet_connect 0.5.1 copy "near_wallet_connect: ^0.5.1" to clipboard
near_wallet_connect: ^0.5.1 copied to clipboard

Drop-in NEAR wallet connection for Flutter — adaptive connect (web redirect, mobile deep links), persistent key storage, and a NearConnectButton widget.

near_wallet_connect #

License: MIT

One button. Every NEAR wallet. Drop-in wallet connection for Flutter — NearConnectButton opens a wallet picker (Intear, HOT, Bitte, HERE, MyNearWallet), and one controller handles wallet selection, connection, and session state. Signing capabilities remain wallet-specific, as described below. Built on near_dart.

NEAR Flutter demo on Android

Add it #

dependencies:
  near_wallet_connect: ^0.5.1

Use it #

Start with the lifecycle-safe ChangeNotifier recipe, or select the Provider, Riverpod, or Bloc/Cubit recipe in the same guide. Each recipe handles and surfaces asynchronous init() failures, keeps the controller alive until initialization settles, and disposes it exactly once so its platform link subscription is cancelled. Do not drop the init() future or dispose the controller while it is still initializing.

The examples below use wallet for the recipe-owned NearWalletController. Tapping this button opens the wallet picker:

NearConnectButton(controller: wallet);

Connected. signer() is available for MyNearWallet and Intear sessions that provision a function-call key. The controller's signMessage is NEP-413 for Intear and HOT. sendTransactions is available for Intear, HOT, Bitte, and HERE. MyNearWallet message/transaction signing stays on the secure adapter redirect APIs.

// MyNearWallet or Intear: gas-only calls signed with a function-call key.
final signer = await wallet.signer();
await signer!.callFunction(
  contractId: AccountId('app.testnet'),
  methodName: 'add_message',
  args: {'text': 'hello'},
);

// Intear or HOT: NEP-413 signing resolves through the wallet bridge/relay.
final signed = await wallet.signMessage(Nep413Payload(
  message: 'Sign in to app.com',
  recipient: 'app.com',
  nonce: generateNep413Nonce(),
));

// Intear, HOT, Bitte, or HERE: payments and deposits approved in the wallet.
await wallet.sendTransactions([
  {
    'receiverId': 'app.testnet',
    'actions': [
      {
        'type': 'FunctionCall',
        'params': {
          'methodName': 'tip',
          'args': {'message': 'gm'},
          'gas': '30000000000000',
          'deposit': '1000000000000000000000000', // 1 NEAR
        },
      },
    ],
  },
]);

For MyNearWallet message and transaction signing, use the secure redirect starter/completion pairs from near_dart; do not use the URL-only builders for new flows:

import 'package:near_dart/near_dart.dart';

final myNearWallet = MyNearWalletAdapter(
  config: MyNearWalletConfig(
    contractId: AccountId('app.testnet'),
    successUrl: 'myapp://wallet/success',
    failureUrl: 'myapp://wallet/failure',
    network: MyNearWalletNetwork.testnet,
  ),
  keyStore: wallet.keyStore,
  launchUrl: openExternalWalletUrl,
);

final request = SignMessageParams(
  message: 'Sign in to app.com',
  recipient: 'app.com',
  nonce: generateNep413Nonce(),
  state: createAndStoreCsrfState(),
);

// Starter: opens a correlated, one-shot flow and launches the wallet.
try {
  await myNearWallet.signMessage(request);
} on NearSdkException catch (error) {
  if (error.code != NearErrorCode.missingCallback) rethrow;
}

// Completion: pass the wallet-emitted callback URI through unchanged.
final signed = await myNearWallet.completeSignMessage(
  signMessageCallbackUri,
  request: request,
);

// Transaction starter/completion use the same correlated callback lifecycle.
try {
  await myNearWallet.signAndSendTransactions(transactions: transactions);
} on NearSdkException catch (error) {
  if (error.code != NearErrorCode.missingCallback) rethrow;
}
final outcomes = myNearWallet.handleTransactionCallback(
  transactionCallbackUri,
);

Keep the original request until completion. Never reconstruct a callback URI from a configured base URL: the callback embedded in each launched wallet URL contains correlation data that must survive unchanged. Completion checks the exact route and correlation value and consumes the flow once, so replay is rejected. completeSignMessage also checks state and verifies the Ed25519 signature over the exact emitted NEP-413 payload, including its callback URL. For authentication, also enforce nonce freshness and recipient server-side and verify that the returned key is authorized for the claimed account.

See example/ for a complete minimal app.

For lifecycle-safe ChangeNotifier, Provider, Riverpod, and Bloc/Cubit setups, see the Flutter architecture recipes.

Both NearWalletSecurityPolicy fields are opt-in:

securityPolicy: const NearWalletSecurityPolicy(
  verifyAccessKeyOnConnect: true,
  transactionFinality: TxExecutionStatus.final_,
),

verifyAccessKeyOnConnect verifies fresh and restored account/key pairs on chain. transactionFinality confirms returned transaction hashes with txStatus. Confirmation does not authenticate unsigned relay metadata. See the security model for wallet-specific scope and residual trust.

Diagnostics And Typed Errors #

Pass an allowlisting logger to the controller. Never add callback URLs, messages, nonces, signatures, request bodies, credentials, or key material.

void nearLogger(NearLogEvent event) {
  final safe = <String, Object?>{
    if (event.metadata['durationMs'] case final value?) 'durationMs': value,
    if (event.metadata['failureCode'] case final value?) 'failureCode': value,
    if (event.metadata['networkId'] case final value?) 'networkId': value,
  };
  print('${event.type.name} ${event.operation} $safe');
}

final wallet = NearWalletController(
  network: MyNearWalletNetwork.testnet,
  contractId: AccountId('app.testnet'),
  logger: nearLogger,
);

switch (wallet.lastException?.code) {
  case NearErrorCode.userRejected:
    showRetry();
  case NearErrorCode.rpcTimeout:
    showRetryLater();
  case NearErrorCode.accessKeyNotFound || NearErrorCode.accessKeyMismatch:
    showReconnect();
  case null:
    break;
  default:
    showError(wallet.error ?? 'Wallet operation failed');
}

wallet.error remains the compatible String? display message; wallet.lastException is the typed NearSdkException?. See Troubleshooting for recovery guidance by error code.

Customize the UI #

Use the default button for fast integration:

NearConnectButton(controller: wallet, compact: true);

Or keep the controller/picker logic and replace the visual states:

NearConnectButton(
  controller: wallet,
  connectBuilder: (context, controller, onPressed) {
    return OutlinedButton.icon(
      onPressed: onPressed,
      icon: const Icon(Icons.account_balance_wallet_outlined),
      label: const Text('Connect'),
    );
  },
  connectedBuilder: (context, controller, onDisconnect) {
    return NearAccountBadge(
      accountId: controller.account!.accountId,
      wallet: controller.walletOption,
      onDisconnect: onDisconnect,
      compact: true,
    );
  },
);

Reusable pieces:

  • NearWalletPicker
  • NearAccountBadge
  • NearBalanceText
  • NearTransactionStatusView

Supported wallets #

Wallet Networks Connect flow signer() signMessage sendTransactions
MyNearWallet testnet + mainnet browser redirect yes secure adapter redirect² secure adapter redirect²
Intear testnet + mainnet native app + WebSocket bridge¹ yes controller controller
HOT mainnet native/Telegram app + relay¹ no controller controller
Bitte testnet + mainnet browser redirect no unsupported controller³
HERE testnet + mainnet universal sign link no not NEP-413 controller³

¹ Resolves in place — no inbound deep link needed. ² Use signMessage / completeSignMessage and signAndSendTransaction(s) / handleTransactionCallback. URL-only builders do not open the pending correlated flow required by the secure completion APIs. ³ Mobile/desktop: the controller waits for the inbound callback. Web full-page navigation cannot return hashes to the same isolate; use the adapter directly. HERE Instant Wallet login (h4n.app) is HOT Wallet. HERE universal links require account_id + public_key on the connect callback. Meteor, Nightly, and Sender are browser-extension / postMessage wallets — there is no Flutter deep-link contract, so they are not faked here.

MyNearWallet remains fully supported until its announced sunset (October 31, 2026). The other wallets are additional options, not replacements — pick per user, at runtime.

Platform setup (one-time) #

The MyNearWallet callback uses a custom URL scheme (default nearsdk://). Register it:

Android — android/app/src/main/AndroidManifest.xml, inside <activity>:

<intent-filter android:autoVerify="false">
  <action android:name="android.intent.action.VIEW"/>
  <category android:name="android.intent.category.DEFAULT"/>
  <category android:name="android.intent.category.BROWSABLE"/>
  <data android:scheme="nearsdk"/>
</intent-filter>

iOS — ios/Runner/Info.plist:

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array><string>nearsdk</string></array>
  </dict>
</array>

Web — no setup; the callback returns to your app URL. Intear and HOT need no callback setup on any platform (responses arrive over their bridges). Bitte uses the same scheme as MyNearWallet; HERE uses <scheme>://callback/here.

How it works #

  • MyNearWallet: full-page redirect (web) or system browser + deep-link callback (mobile). Connecting provisions a function-call key, stored so gas-only calls sign locally afterwards.
  • Intear: a per-request WebSocket bridge session + intear:// deep link; the wallet's response arrives over the socket. Connecting can also add a function-call key, so signer() works here too.
  • HOT: requests are queued on HOT's relay and opened via hotwallet://; the app polls the relay for the response. This is HERE Instant Wallet.
  • Bitte: browser redirect to wallet.bitte.ai / testnet.wallet.bitte.ai. Connect returns account_id + public_key and does not add a local function-call key. Payments use /sign-transaction and return transactionHashes.
  • HERE: universal links https://my.herewallet.app/call/{b58} and /sign/{b58} with ?returnUrl=. Success is ?success=hash,hash; failure is ?failure=text. Connect needs account_id and public_key on that callback.
  • Intear and HOT wallet-produced NEP-413 signatures are verified locally. Connect and transaction metadata are not all signed; relays remain availability dependencies. Bitte/HERE callback hashes are not signed wallet assertions; enable transactionFinality for on-chain confirmation.
  • Keys persist via SecureKeyStore by default (Android Keystore / Apple Keychain / Windows DPAPI / Linux libsecret); on web — where no OS secret storage exists — a plain SharedPrefsKeyStore is used. Sessions from older versions migrate to secure storage automatically. Details: docs/security.md.
  • Legacy HOT sessions that predate authentic public-key persistence are cleared during init() and require one reconnect.

License #

MIT

0
likes
160
points
94
downloads
screenshot

Documentation

API reference

Publisher

verified publisher0xj.dev

Weekly Downloads

Drop-in NEAR wallet connection for Flutter — adaptive connect (web redirect, mobile deep links), persistent key storage, and a NearConnectButton widget.

Repository (GitHub)
View/report issues

Topics

#near #wallet #flutter #web3 #blockchain

License

MIT (license)

Dependencies

app_links, flutter, flutter_secure_storage, near_dart, shared_preferences, url_launcher

More

Packages that depend on near_wallet_connect