Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/frol/near-connect-ios/llms.txt

Use this file to discover all available pages before exploring further.

NEARWalletManager

The NEARWalletManager class is the primary interface for integrating NEAR blockchain functionality into your iOS app. It manages wallet connections, handles transaction signing, and maintains persistent sessions.

Overview

NEARWalletManager is an ObservableObject that owns a persistent WKWebView running the near-connect JavaScript bridge. The WebView lives for the lifetime of the manager, ensuring wallet sessions and JavaScript state survive across sheet presentations.
import NEARConnect

@MainActor
public class NEARWalletManager: ObservableObject

Properties

currentAccount

The currently connected NEAR account, or nil if no wallet is connected.
@Published public var currentAccount: NEARAccount?
currentAccount
NEARAccount?
The authenticated account information, including account ID, public key, and wallet ID. Automatically persisted across app launches.

isBusy

Indicates whether an operation is currently in progress.
@Published public var isBusy: Bool
isBusy
Bool
true when a wallet operation (connect, transaction, sign message) is in progress. Use this to show loading indicators.

lastError

The most recent error message from wallet operations.
@Published public var lastError: String?
lastError
String?
Human-readable error message from the last failed operation, or nil if no error occurred.

isBridgeReady

Indicates whether the JavaScript bridge is ready for operations.
@Published public private(set) var isBridgeReady: Bool
isBridgeReady
Bool
true when the near-connect bridge has loaded and is ready to handle wallet operations. Read-only from outside the class.

showWalletUI

Controls whether the wallet WebView should be presented to the user.
@Published public var showWalletUI: Bool
showWalletUI
Bool
Set to true to present the wallet interface for connect flows, transaction approval, or message signing.

network

The NEAR network for wallet connections.
@Published public var network: Network
network
Network
Either .mainnet or .testnet. Defaults to .mainnet.
public enum Network: String, Sendable {
    case mainnet
    case testnet
}

isSignedIn

Computed property indicating whether a wallet is currently connected.
public var isSignedIn: Bool
isSignedIn
Bool
Returns true if currentAccount is not nil.

Initialization

init(userDefaults:)

Creates a new wallet manager instance.
public init(userDefaults: UserDefaults = .standard)
userDefaults
UserDefaults
default:".standard"
The UserDefaults instance for persisting account data. Defaults to the standard user defaults.
Example:
import NEARConnect
import SwiftUI

@main
struct MyApp: App {
    @StateObject private var walletManager = NEARWalletManager()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(walletManager)
        }
    }
}

Connection Methods

connect()

Presents the wallet selector to the user.
public func connect()
This method sets up the wallet selector UI and presents it. The user can choose from available NEAR wallets to connect. Example:
Button("Connect Wallet") {
    walletManager.connect()
}

connect(walletId:)

Connects with a specific wallet by ID.
public func connect(walletId: String)
walletId
String
required
The wallet identifier (e.g., “meteor-wallet”, “my-near-wallet”).
Example:
Button("Connect with Meteor") {
    walletManager.connect(walletId: "meteor-wallet")
}

connectAndSignMessage(message:recipient:nonce:)

Connects a wallet and requests a message signature in a single step.
public func connectAndSignMessage(
    message: String,
    recipient: String,
    nonce: Data? = nil
) async throws -> SignInWithMessageResult
message
String
required
The message to sign (NEP-413 format).
recipient
String
required
The intended recipient of the signed message (usually your app’s domain or contract ID).
nonce
Data
default:"nil"
Optional 32-byte nonce for the signature. If nil, a random nonce is generated.
SignInWithMessageResult
Struct
Contains the connected account and optional signedMessage string.
Throws: NEARError if the operation fails, user cancels, or bridge is not ready. Example:
Task {
    do {
        let result = try await walletManager.connectAndSignMessage(
            message: "Welcome to MyApp!",
            recipient: "myapp.near"
        )
        print("Connected: \(result.account.accountId)")
        if let signature = result.signedMessage {
            print("Signature: \(signature)")
        }
    } catch {
        print("Connection failed: \(error)")
    }
}

disconnect()

Disconnects the current wallet.
public func disconnect()
Clears the current account, removes persisted data, and resets the connection state. Example:
Button("Disconnect") {
    walletManager.disconnect()
}

Transaction Methods

sendNEAR(to:amountYocto:)

Sends NEAR tokens to another account.
public func sendNEAR(
    to receiverId: String,
    amountYocto: String
) async throws -> TransactionResult
receiverId
String
required
The NEAR account ID of the recipient.
amountYocto
String
required
The amount to send in yoctoNEAR (1 NEAR = 10²⁴ yoctoNEAR). Use toYoctoNEAR(_:) to convert from NEAR.
TransactionResult
Struct
Contains transactionHashes array and optional rawResult string.
Throws: NEARError.notSignedIn if no wallet is connected, NEARError.operationInProgress if another operation is active, or other NEARError variants on failure. Example:
Task {
    do {
        guard let yoctoAmount = NEARWalletManager.toYoctoNEAR("1.5") else {
            print("Invalid amount")
            return
        }
        
        let result = try await walletManager.sendNEAR(
            to: "alice.near",
            amountYocto: yoctoAmount
        )
        print("Transaction hash: \(result.transactionHashes.first ?? "")")
    } catch {
        print("Transfer failed: \(error)")
    }
}

callFunction(contractId:methodName:args:gas:deposit:)

Calls a smart contract function.
public func callFunction(
    contractId: String,
    methodName: String,
    args: [String: Any] = [:],
    gas: String = "30000000000000",
    deposit: String = "0"
) async throws -> TransactionResult
contractId
String
required
The NEAR account ID of the smart contract.
methodName
String
required
The name of the contract method to call.
args
[String: Any]
default:"[:]"
JSON-serializable arguments to pass to the contract method.
gas
String
default:"30000000000000"
Gas limit for the transaction in gas units (30 TGas default).
deposit
String
default:"0"
NEAR tokens to attach to the call in yoctoNEAR.
TransactionResult
Struct
Contains transactionHashes array and optional rawResult string.
Throws: NEARError if the operation fails or user rejects the transaction. Example:
Task {
    do {
        let result = try await walletManager.callFunction(
            contractId: "nft.example.near",
            methodName: "nft_mint",
            args: [
                "token_id": "123",
                "receiver_id": walletManager.currentAccount?.accountId ?? ""
            ],
            gas: "50000000000000",
            deposit: "10000000000000000000000" // 0.01 NEAR
        )
        print("NFT minted: \(result.transactionHashes.first ?? "")")
    } catch {
        print("Contract call failed: \(error)")
    }
}

signAndSendTransaction(receiverId:actions:)

Signs and sends a transaction with custom actions.
public func signAndSendTransaction(
    receiverId: String,
    actions: [[String: Any]]
) async throws -> TransactionResult
receiverId
String
required
The account ID that will receive/process this transaction.
actions
[[String: Any]]
required
Array of action objects. Each action has a "type" field (“Transfer”, “FunctionCall”, “CreateAccount”, etc.) and a "params" dictionary.
TransactionResult
Struct
Contains transactionHashes array and optional rawResult string.
Example:
let actions: [[String: Any]] = [
    [
        "type": "FunctionCall",
        "params": [
            "methodName": "set_status",
            "args": "eyJzdGF0dXMiOiAiSGVsbG8gV29ybGQhIn0=", // base64
            "gas": "30000000000000",
            "deposit": "0"
        ]
    ]
]

Task {
    do {
        let result = try await walletManager.signAndSendTransaction(
            receiverId: "contract.near",
            actions: actions
        )
        print("Transaction sent: \(result.transactionHashes)")
    } catch {
        print("Transaction failed: \(error)")
    }
}

Message Signing Methods

signMessage(message:recipient:nonce:)

Signs an off-chain message using NEP-413.
public func signMessage(
    message: String,
    recipient: String,
    nonce: Data? = nil
) async throws -> MessageSignResult
message
String
required
The message to sign.
recipient
String
required
The intended recipient (usually your app’s domain or contract ID).
nonce
Data
default:"nil"
Optional 32-byte nonce. If nil, a random nonce is generated.
MessageSignResult
Struct
Contains accountId, publicKey, and signature (all optional strings).
Throws: NEARError.notSignedIn if no wallet is connected, or other NEARError variants on failure. Example:
Task {
    do {
        let result = try await walletManager.signMessage(
            message: "Authenticate with MyApp",
            recipient: "myapp.near"
        )
        print("Signature: \(result.signature ?? "")")
    } catch {
        print("Signing failed: \(error)")
    }
}

signDelegateActions(delegateActions:)

Signs delegate actions for meta transactions (NEP-366).
public func signDelegateActions(
    delegateActions: [[String: Any]]
) async throws -> DelegateActionResult
delegateActions
[[String: Any]]
required
Array of delegate action dictionaries, each containing "receiverId" (String) and "actions" (array of action objects).
DelegateActionResult
Struct
Contains rawResult with the signed payload from the wallet.
The wallet signs the actions without broadcasting them. A relayer service is responsible for submitting the signed delegate actions to the network. Throws: NEARError if the operation fails or user rejects. Example:
let delegateActions = [
    [
        "receiverId": "contract.near",
        "actions": [
            [
                "type": "FunctionCall",
                "params": [
                    "methodName": "increment",
                    "args": "",
                    "gas": "30000000000000",
                    "deposit": "0"
                ]
            ]
        ]
    ]
]

Task {
    do {
        let result = try await walletManager.signDelegateActions(
            delegateActions: delegateActions
        )
        // Send result.rawResult to your relayer service
        print("Signed delegate action: \(result.rawResult ?? "")")
    } catch {
        print("Signing failed: \(error)")
    }
}

RPC Methods

viewAccount(_:)

Queries account information via NEAR RPC.
public func viewAccount(_ accountId: String? = nil) async throws -> [String: Any]
accountId
String
default:"nil"
The account ID to query. If nil, uses the current connected account.
result
[String: Any]
Dictionary containing account information: amount (balance in yoctoNEAR), locked, code_hash, storage_usage, storage_paid_at, and block_height.
Throws: NEARError.notSignedIn if no account specified and not signed in, or NEARError.rpcError on RPC failures. Example:
Task {
    do {
        let accountInfo = try await walletManager.viewAccount()
        if let balance = accountInfo["amount"] as? String {
            let near = NEARWalletManager.formatNEAR(yoctoNEAR: balance)
            print("Balance: \(near) NEAR")
        }
    } catch {
        print("Failed to fetch account: \(error)")
    }
}

Utility Methods

formatNEAR(yoctoNEAR:)

Converts yoctoNEAR string to human-readable NEAR amount.
public static func formatNEAR(yoctoNEAR: String) -> String
yoctoNEAR
String
required
The amount in yoctoNEAR (1 NEAR = 10²⁴ yoctoNEAR).
formatted
String
Human-readable NEAR amount with up to 5 decimal places.
Example:
let yocto = "1500000000000000000000000"
let near = NEARWalletManager.formatNEAR(yoctoNEAR: yocto)
print("Amount: \(near) NEAR") // "Amount: 1.5 NEAR"

toYoctoNEAR(_:)

Converts NEAR amount string to yoctoNEAR string.
public static func toYoctoNEAR(_ near: String) -> String?
near
String
required
The amount in NEAR (e.g., “1.5”).
yocto
String?
The amount in yoctoNEAR, or nil if the input is invalid.
Example:
if let yocto = NEARWalletManager.toYoctoNEAR("1.5") {
    print("YoctoNEAR: \(yocto)") // "1500000000000000000000000"
}

closePopups()

Removes all popup WebViews (wallet pages opened via window.open).
public func closePopups()
Use this to manually clean up wallet UI popups if needed. Generally handled automatically after operations complete. Example:
walletManager.closePopups()

Nested Types

Network

Network selection for wallet connections.
public enum Network: String, Sendable {
    case mainnet
    case testnet
}

SignInWithMessageResult

Result of connecting a wallet with a signed message.
public struct SignInWithMessageResult {
    public let account: NEARAccount
    public let signedMessage: String?
}
account
NEARAccount
The connected account information.
signedMessage
String?
The signed message payload returned by the wallet, or nil if the wallet does not support signInAndSignMessage.

TransactionResult

Result of a signed and sent transaction.
public struct TransactionResult {
    public let transactionHashes: [String]
    public let rawResult: String?
}
transactionHashes
[String]
Array of transaction hash strings.
rawResult
String?
Raw JSON result from the wallet, if available.

MessageSignResult

Result of a signed message.
public struct MessageSignResult {
    public let accountId: String?
    public let publicKey: String?
    public let signature: String?
}
accountId
String?
The account that signed the message.
publicKey
String?
The public key used for signing.
signature
String?
The signature string (JSON format).

DelegateActionResult

Result of signed delegate actions.
public struct DelegateActionResult {
    public let rawResult: String?
}
rawResult
String?
Raw JSON result from the wallet containing the signed delegate actions.

See Also

Build docs developers (and LLMs) love