Skip to content

Commit

Permalink
chore: handle chainId and accounts data on batch request (#169)
Browse files Browse the repository at this point in the history
* chore: handle chainId and accounts data on batch request

* Refactor message handling

* Add tests for batch handling
  • Loading branch information
elefantel authored Jul 15, 2024
1 parent 5430512 commit 6408dc3
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
32 changes: 31 additions & 1 deletion Example/Tests/EthereumTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -567,15 +567,45 @@ class EthereumTests: XCTestCase {
let requestId = Ethereum.BATCH_CONNECTION_ID
let request = SubmittedRequest(method: "metamask_batch")
ethereum.submittedRequests[requestId] = request
let ethereumMainnet = "0x1"
let accounts = ["0x1234"]

let resultData: [String: Any] = [
"result": [["0x1234"], "0x1"]
"result": [["0x1234"], ethereumMainnet]
]

ethereum.receiveResponse(resultData, id: requestId)

XCTAssertTrue(mockEthereumDelegate.chainIdChangedCalled)
XCTAssertEqual(mockEthereumDelegate.chainId, ethereumMainnet)
XCTAssertTrue(mockEthereumDelegate.accountChangedCalled)
XCTAssertEqual(mockEthereumDelegate.account, accounts.first)
}

func testReceiveDataResponseWithMetamaskBatch() {
let requestId = Ethereum.BATCH_CONNECTION_ID
let request = SubmittedRequest(method: "metamask_batch")
ethereum.submittedRequests[requestId] = request
let polygonChainId = "0x89"
let accounts = ["0x1234"]

let message: [String: Any] = [
"data": [
"id": requestId,
"result": ["0xf9990f422f9a", "0x8904d14b2c67b3988ca27"],
"chainId": polygonChainId,
"accounts": accounts
]
]

let data = message["data"] as? [String: Any] ?? [:]

ethereum.handleMessage(data)

XCTAssertTrue(mockEthereumDelegate.chainIdChangedCalled)
XCTAssertEqual(mockEthereumDelegate.chainId, polygonChainId)
XCTAssertTrue(mockEthereumDelegate.accountChangedCalled)
XCTAssertEqual(mockEthereumDelegate.account, accounts.first)
}

// MARK: Events
Expand Down
14 changes: 12 additions & 2 deletions Sources/metamask-ios-sdk/Classes/Ethereum/Ethereum.swift
Original file line number Diff line number Diff line change
Expand Up @@ -766,8 +766,18 @@ public class Ethereum {
updateAccount(account)
}
updateChainId(chainId)
} else if let result = data["result"] {
sendResult(result, id: id)
} else {
if
let accounts = data["accounts"] as? [String],
let account = accounts.first {
updateAccount(account)
}
if let chainId = data["chainId"] as? String {
updateChainId(chainId)
}
if let result = data["result"] {
sendResult(result, id: id)
}
}
default:
if let chainId = data["chainId"] as? String {
Expand Down

0 comments on commit 6408dc3

Please sign in to comment.