> ## Documentation Index
> Fetch the complete documentation index at: https://docs.polygon.technology/llms.txt
> Use this file to discover all available pages before exploring further.

# Swift Blockchain Interaction

> Send transactions, call contracts, sign payloads, and verify signatures with the Swift OMS Wallet SDK.

All wallet operations require an active wallet session. Complete auth first, then use `oms.wallet`.

```swift theme={null}
guard let walletAddress = oms.wallet.walletAddress else {
    throw NSError(domain: "App", code: 1, userInfo: [NSLocalizedDescriptionKey: "No active wallet"])
}
```

## Supported Networks

Use the SDK network registry when passing `network` to wallet and indexer calls.

```swift theme={null}
let amoy = oms.findNetworkById(chainId: 80002) ?? .polygonAmoy
let polygon = oms.findNetworkByName(name: "polygon")

if let polygon {
    print(amoy.displayName, polygon.id)
}

for network in oms.supportedNetworks {
    print(network.id, network.displayName, network.nativeTokenSymbol)
}
```

**Parameters**

`findNetworkById(chainId:)` takes a numeric chain ID. `findNetworkByName(name:)` takes a registry name such as `polygon`, `amoy`, or `base-sepolia`.

**Returns**

`oms.supportedNetworks` returns every `Network` supported by the SDK build. Lookup helpers return a `Network?`.

## Send A Transaction

`sendTransaction` sends native tokens. Amounts are raw base-unit integer strings. Use `parseUnits` to convert a display value without floating-point precision loss.

```swift theme={null}
let value = try parseUnits(value: "0.01", decimals: 18)

let tx = try await oms.wallet.sendTransaction(
    network: .polygonAmoy,
    to: "0x1111111111111111111111111111111111111111",
    value: value
)

print("Transaction:", tx.txnHash ?? tx.txnId)
```

**Parameters**

| Parameter         | Type                              | Description                                                               |
| ----------------- | --------------------------------- | ------------------------------------------------------------------------- |
| `network`         | `Network`                         | Supported SDK network, such as `.polygon` or `.polygonAmoy`.              |
| `to`              | `String`                          | Recipient address.                                                        |
| `value`           | `String`                          | Raw base-unit native token value.                                         |
| `selectFeeOption` | `FeeOptionSelector?`              | Optional fee option selector.                                             |
| `mode`            | `TransactionMode`                 | Advanced execution option. Omit it for the default behavior.              |
| `waitForStatus`   | `Bool`                            | Defaults to `true`. Set to `false` to return immediately after execution. |
| `statusPolling`   | `TransactionStatusPollingOptions` | Optional fast poll, slow poll, and timeout configuration.                 |

**Returns**

Returns `SendTransactionResponse`.

| Field     | Type                | Description                                       |
| --------- | ------------------- | ------------------------------------------------- |
| `txnId`   | `String`            | Wallet transaction ID.                            |
| `status`  | `TransactionStatus` | Latest transaction status returned by OMS Wallet. |
| `txnHash` | `String?`           | Onchain transaction hash when available.          |

## Send Encoded Calldata

Use the request overload when you already have encoded calldata.

```swift theme={null}
let tx = try await oms.wallet.sendTransaction(
    network: .polygonAmoy,
    request: SendTransactionRequest(
        to: "0x2222222222222222222222222222222222222222",
        value: "0",
        data: "0xa9059cbb000000000000000000000000..."
    )
)

print("Contract transaction:", tx.txnHash ?? tx.txnId)
```

**Parameters**

| Parameter         | Type                              | Description                                                               |
| ----------------- | --------------------------------- | ------------------------------------------------------------------------- |
| `network`         | `Network`                         | Supported SDK network.                                                    |
| `request`         | `SendTransactionRequest`          | Request with `to`, raw `value`, and optional encoded calldata `data`.     |
| `selectFeeOption` | `FeeOptionSelector?`              | Optional fee option selector.                                             |
| `waitForStatus`   | `Bool`                            | Defaults to `true`. Set to `false` to return immediately after execution. |
| `statusPolling`   | `TransactionStatusPollingOptions` | Optional fast poll, slow poll, and timeout configuration.                 |

**Returns**

Returns `SendTransactionResponse`.

## Convert Token Values

Use `parseUnits` before sending display amounts to the wallet API, and `formatUnits` when showing raw base-unit balances in the UI.

```swift theme={null}
let rawUsdc = try parseUnits(value: "1.23", decimals: 6)
print(rawUsdc) // "1230000"

let displayUsdc = try formatUnits(value: rawUsdc, decimals: 6)
print(displayUsdc) // "1.23"
```

**Parameters**

| Function      | Parameter  | Type     | Description                             |
| ------------- | ---------- | -------- | --------------------------------------- |
| `parseUnits`  | `value`    | `String` | Display amount to convert.              |
| `parseUnits`  | `decimals` | `Int`    | Token decimals. Defaults to `18`.       |
| `formatUnits` | `value`    | `String` | Raw base-unit integer string to format. |
| `formatUnits` | `decimals` | `Int`    | Token decimals. Defaults to `18`.       |

**Returns**

Both functions return `String`. They throw `UnitConversionError` for invalid decimals or invalid numeric strings. `parseUnits` rounds fractional precision beyond `decimals` to the nearest base unit.

## Call A Contract With Method And Args

Use `callContract` for state-changing contract methods. The SDK prepares the contract call, executes it, and polls for transaction status.

```swift theme={null}
let amount = try parseUnits(value: "1", decimals: 6)

let tx = try await oms.wallet.callContract(
    network: .polygonAmoy,
    contract: "0x2222222222222222222222222222222222222222",
    method: "transfer(address,uint256)",
    args: [
        AbiArg(type: "address", value: .string("0x1111111111111111111111111111111111111111")),
        AbiArg(type: "uint256", value: .string(amount))
    ]
)

print("Contract call:", tx.txnHash ?? tx.txnId)
```

**Parameters**

| Parameter         | Type                              | Description                                                               |
| ----------------- | --------------------------------- | ------------------------------------------------------------------------- |
| `network`         | `Network`                         | Supported SDK network.                                                    |
| `contract`        | `String`                          | Contract address to call.                                                 |
| `method`          | `String`                          | ABI method signature, such as `transfer(address,uint256)`.                |
| `args`            | `[AbiArg]?`                       | Method arguments as ABI args.                                             |
| `selectFeeOption` | `FeeOptionSelector?`              | Optional fee option selector.                                             |
| `mode`            | `TransactionMode`                 | Advanced execution option. Omit it for the default behavior.              |
| `waitForStatus`   | `Bool`                            | Defaults to `true`. Set to `false` to return immediately after execution. |
| `statusPolling`   | `TransactionStatusPollingOptions` | Optional fast poll, slow poll, and timeout configuration.                 |

**Returns**

Returns `SendTransactionResponse`.

## Select A Fee Option

When OMS Wallet returns fee options, the SDK selects a fee option before execution. If no selector is provided, the SDK uses the first required fee option.

On testnets, all transactions are sponsored and do not require picking a fee option.

Use `FeeOptionSelector.firstAvailable` when you want the SDK to choose the first fee option whose `availableRaw` balance covers the quoted fee `value`. This is the standard selector for apps that do not need a custom fee-token picker.

```swift theme={null}
let tx = try await oms.wallet.sendTransaction(
    network: .polygon,
    to: "0x1111111111111111111111111111111111111111",
    value: "0",
    selectFeeOption: .firstAvailable
)
```

You can also provide a custom selector.

```swift theme={null}
let tx = try await oms.wallet.sendTransaction(
    network: .polygon,
    to: "0x1111111111111111111111111111111111111111",
    value: "0",
    selectFeeOption: .custom { options in
        options.first?.selection
    }
)
```

**Parameters**

`FeeOptionSelector` receives `[FeeOptionWithBalance]`. Each item includes `feeOption`, `selection`, and optional `balance`, `available`, `availableRaw`, and `decimals` fields.

**Returns**

Return `FeeOptionSelection?` from custom selectors.

## Polling And Status

Transaction helpers execute and poll for transaction status. Fetch status directly when you have a Wallet transaction ID.

```swift theme={null}
let status = try await oms.wallet.getTransactionStatus(txnId: "txn-id")

print("Status:", status.status)
print("Transaction hash:", status.txnHash ?? "pending")
```

**Parameters**

| Parameter | Type     | Description                                                            |
| --------- | -------- | ---------------------------------------------------------------------- |
| `txnId`   | `String` | Wallet transaction ID returned by `sendTransaction` or `callContract`. |

**Returns**

Returns `TransactionStatusResponse`.

| Field     | Type                | Description                              |
| --------- | ------------------- | ---------------------------------------- |
| `status`  | `TransactionStatus` | Latest Wallet transaction status.        |
| `txnHash` | `String?`           | Onchain transaction hash when available. |

Transaction writes can throw `OmsSdkError` with transaction recovery details. If `sendTransaction` or `callContract` throws `.transactionExecutionUnconfirmed`, preserve `error.txnId` and do not resend the same write automatically. The SDK prepared the transaction, but could not confirm whether execution was submitted. If it throws `.transactionStatusLookupFailed`, the transaction was submitted, but post-submit status polling failed. Retry `getTransactionStatus(txnId:)` with the returned `txnId`.

```swift theme={null}
do {
    let tx = try await oms.wallet.sendTransaction(
        network: .polygonAmoy,
        to: "0x1111111111111111111111111111111111111111",
        value: "0"
    )
    print("Transaction:", tx.txnHash ?? tx.txnId)
} catch let error as OmsSdkError {
    switch error.code {
    case .transactionExecutionUnconfirmed:
        print("Execution unconfirmed:", error.txnId ?? "unknown")
    case .transactionStatusLookupFailed:
        print("Retry status lookup:", error.txnId ?? "unknown")
    default:
        throw error
    }
}
```

## Sign A Message

`signMessage` returns a hex-encoded signature for the active wallet.

```swift theme={null}
let signature = try await oms.wallet.signMessage(
    network: .polygonAmoy,
    message: "Hello from OMS"
)

print("Signature:", signature)
```

**Parameters**

| Parameter | Type      | Description                |
| --------- | --------- | -------------------------- |
| `network` | `Network` | Supported SDK network.     |
| `message` | `String`  | Plaintext message to sign. |

**Returns**

Returns `String`, the hex-encoded signature.

## Verify A Message Signature

`isValidMessageSignature` verifies a message signature against the wallet address you provide.

```swift theme={null}
let isValid = try await oms.wallet.isValidMessageSignature(
    network: .polygonAmoy,
    walletAddress: walletAddress,
    message: "Hello from OMS",
    signature: signature
)

print("Signature valid:", isValid)
```

**Parameters**

| Parameter       | Type      | Description                                     |
| --------------- | --------- | ----------------------------------------------- |
| `network`       | `Network` | Supported SDK network.                          |
| `walletAddress` | `String`  | Wallet address to verify the signature against. |
| `message`       | `String`  | Original plaintext message.                     |
| `signature`     | `String`  | Hex-encoded signature to verify.                |

**Returns**

Returns `Bool`.

## Sign Typed Data

Use `signTypedData` for EIP-712 typed data. Build the payload with `WebRPCJSONValue` values.

```swift theme={null}
let typedData: WebRPCJSONValue = .object([
    "domain": .object([
        "name": .string("Example App"),
        "version": .string("1"),
        "chainId": .integer(80002)
    ]),
    "types": .object([
        "Message": .array([
            .object([
                "name": .string("contents"),
                "type": .string("string")
            ])
        ])
    ]),
    "primaryType": .string("Message"),
    "message": .object([
        "contents": .string("Hello from OMS")
    ])
])

let typedSignature = try await oms.wallet.signTypedData(
    network: .polygonAmoy,
    typedData: typedData
)
```

**Parameters**

| Parameter   | Type              | Description                 |
| ----------- | ----------------- | --------------------------- |
| `network`   | `Network`         | Supported SDK network.      |
| `typedData` | `WebRPCJSONValue` | EIP-712 typed-data payload. |

**Returns**

Returns `String`, the hex-encoded signature.

## Verify Typed Data

Verify an EIP-712 typed-data signature.

```swift theme={null}
let typedDataValid = try await oms.wallet.isValidTypedDataSignature(
    network: .polygonAmoy,
    walletAddress: walletAddress,
    typedData: typedData,
    signature: typedSignature
)
```

**Parameters**

| Parameter       | Type              | Description                                     |
| --------------- | ----------------- | ----------------------------------------------- |
| `network`       | `Network`         | Supported SDK network.                          |
| `walletAddress` | `String`          | Wallet address to verify the signature against. |
| `typedData`     | `WebRPCJSONValue` | Original EIP-712 typed-data payload.            |
| `signature`     | `String`          | Hex-encoded signature to verify.                |

**Returns**

Returns `Bool`.
