Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#846: change minimum version of CryptoSwift dependency #848

Open
wants to merge 21 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
39eafd6
renamed callContractMethod to call for ReadOperation
albertopeam Jan 22, 2023
763ed34
Merge pull request #735 from albertopeam/feature/rename-callContractM…
JeneaVranceanu Jan 23, 2023
a85a539
Merge branch 'develop' into chore/develop-v4.0-up-to-date
JeneaVranceanu Jan 24, 2023
0e19adb
Merge pull request #740 from JeneaVranceanu/chore/develop-v4.0-up-to-…
yaroslavyaroslav Jan 26, 2023
2f0cedb
renamed options with transaction
albertopeam Feb 25, 2023
318f8da
API update: input argument renaming and potentially expansion of allo…
JeneaVranceanu Mar 9, 2023
5ebb1d9
Make -createNewAccount- an internal function and remove -password- ar…
Apr 28, 2023
49cab7d
chore: merged with develop
JeneaVranceanu May 2, 2023
f0905c2
Merge pull request #816 from JeneaVranceanu/develop-v4-update
JeneaVranceanu May 3, 2023
1035db1
chore: merged with develop-4.0
JeneaVranceanu May 3, 2023
c66d204
fix: createNewAccount refactoring
JeneaVranceanu May 3, 2023
fa0edd3
chore: added more of personal_sign test cases
JeneaVranceanu Nov 25, 2023
13181b4
chore: comments + docs
JeneaVranceanu Nov 26, 2023
6fa5667
Merge branch 'develop' into chore/more-sign-tests
JeneaVranceanu Jan 9, 2024
6177c46
Merge branch 'develop' into develop-4.0
JeneaVranceanu Jan 16, 2024
ed830e6
Merge branch 'develop' into develop-4.0
JeneaVranceanu Jan 16, 2024
e8b3cdf
Merge pull request #842 from JeneaVranceanu/develop-4.0
yaroslavyaroslav Jan 16, 2024
5614659
Merge branch 'develop-4.0' into chore/more-sign-tests
JeneaVranceanu Jan 24, 2024
f730f02
Merge pull request #839 from JeneaVranceanu/chore/more-sign-tests
yaroslavyaroslav Feb 7, 2024
097adaf
chore: removing cocoapods support (#840)
JeneaVranceanu Feb 8, 2024
1c82a2a
#846: change minimum version of CryptoSwift dependency
Feb 10, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/macOS-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ on:
- hotfix
paths:
- Packag*.swift
- web3swift.podspec
- Cartfile
- Sources/**
- 'Tests/**'
Expand Down
12 changes: 5 additions & 7 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,11 @@ Package.pins
*/.swiftpm/**
Package.resolved

# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
#
Example/**/Pods
# Pods
Pods/
Podfile
Podfile.lock
*.podspec

# Carthage
#
Expand Down
2 changes: 0 additions & 2 deletions CONTRIBUTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ In ci/cd we’re using Xcode test plans feature to spread tests to local and rem
Please add any files unused due build process to `excludeFiles` array in `Package.swift`.
### Carthage
Please do not forget to add & remove all new or dropped files and dependencies in carthage `.xcodeproj` file if you’re working with project anywhere but carthage project.
### Cocoapods
Please do not forget to add & remove all dependencies within `web3swift.podspec` file.
### GitHub actions
You’re able to use our github actions checks in your fork without needing to make PR to this repo. To get that just add your branch name to the branch list in file on path `.github/actions/ci.yml` to let the magic happening like follow:

Expand Down
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/attaswift/BigInt.git", from: "5.3.0"),
.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", from: "1.5.1")
.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", from: "1.8.0")
],
targets: [
.target(name: "secp256k1"),
Expand Down
82 changes: 49 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,23 @@
[Join our discord](https://discord.gg/8bHCNmhS7x) or [Telegram](https://t.me/web3swift) if you need support or want to contribute to web3swift development!

![matter-github-swift](https://github.com/web3swift-team/web3swift/blob/develop/web3swift-logo.png)
[![Web3swift CI](https://github.com/web3swift-team/web3swift/actions/workflows/macOS-12.yml/badge.svg)](https://github.com/web3swift-team/web3swift/actions/workflows/macOS-12.yml)
[![Swift](https://img.shields.io/badge/Swift-5.4-orange.svg?style=flat)](https://developer.apple.com/swift/)
[![Platform](https://img.shields.io/cocoapods/p/web3swift?style=flat)](http://cocoapods.org/pods/web3swift)
[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/web3swift?style=flat)](http://cocoapods.org/pods/web3swift)
[![Web3swift CI](https://github.com/web3swift-team/web3swift/actions/workflows/macOS-tests.yml/badge.svg)](https://github.com/web3swift-team/web3swift/actions/workflows/macOS-tests.yml)
[![Swift](https://img.shields.io/badge/Swift-5.5-f26118.svg?style=flat)](https://developer.apple.com/swift/)
[![License](https://img.shields.io/cocoapods/l/web3swift.svg?style=flat)](https://github.com/web3swift-team/web3swift/blob/master/LICENSE.md)
[![support](https://brianmacdonald.github.io/Ethonate/svg/eth-support-blue.svg)](https://brianmacdonald.github.io/Ethonate/address#0xe22b8979739d724343bd002f9f432f5990879901)
[![Stackoverflow](https://img.shields.io/badge/stackoverflow-ask-blue.svg)](https://stackoverflow.com/questions/tagged/web3swift)
<!-- [![support](https://brianmacdonald.github.io/Ethonate/svg/eth-support-blue.svg)](https://brianmacdonald.github.io/Ethonate/address#0xe22b8979739d724343bd002f9f432f5990879901) -->

---

<!-- MarkdownTOC -->

- [Core features](#core-features)
- [Core Features](#core-features)
- [Installation](#installation)
- [Swift Package](#swift-package)
- [CocoaPods](#cocoapods)
- [Example usage](#example-usage)
- [Create Web3 Provider](#create-web3-provider)
- [Create Web3 Object](#create-web3-object)
- [Send Ether](#send-ether)
- [Contract read method](#contract-read-method)
- [Write Transaction and call smart contract method](#write-transaction-and-call-smart-contract-method)
Expand All @@ -48,11 +48,11 @@
- [x] :thought_balloon: Interaction with remote node via **JSON RPC**
- [x] 🔐 Local **keystore management** (`geth` compatible)
- [x] 🤖 Smart-contract **ABI parsing**
- [x] 🔓**ABI decoding** (V2 is supported with return of structures from public functions. Part of 0.4.22 Solidity compiler)
- [x] 🔓**ABI decoding** (V2 is supported with a return of structures from public functions. Part of 0.4.22 Solidity compiler)
- [x] 🕸Ethereum Name Service **(ENS) support** - a secure & decentralised way to address resources both on and off the blockchain using simple, human-readable names
- [x] :arrows_counterclockwise: **Smart contracts interactions** (read/write)
- [x] ⛩ **Infura support**
- [x] ⚒ **Parsing TxPool** content into native values (ethereum addresses and transactions) - easy to get pending transactions
- [x] ⚒ **Parsing TxPool** content into native values (Ethereum addresses and transactions) - easy to get pending transactions
- [x] 🖇 **Event loops** functionality
- [x] 🕵️‍♂️ Possibility to **add or remove "middleware" that intercepts**, modifies and even **cancel transaction** workflow on stages "before assembly", "after assembly" and "before submission"
- [x] ✅**Literally following the standards** (BIP, EIP, etc):
Expand All @@ -66,7 +66,7 @@

## Installation

### Swift Package (Recommended)
### Swift Package
The [Swift Package Manager](https://swift.org/package-manager/ "") is a tool for automating the distribution of Swift code that is well integrated with Swift build system.

Once you have your Swift package set up, adding `web3swift` as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`.
Expand All @@ -89,30 +89,45 @@ import Web3Core

### CocoaPods

[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:
CocoaPods is not supported.

```bash
$ sudo gem install cocoapods
### Create Web3 Provider
Currently, web3swift supports only HTTP providers. WebSocket provider support was removed and is planned to be rebuilt from scratch.
To create a Web3HttpProvider you only need an RPC URL:
```swift
try await Web3HttpProvider(url: rpcUrl)
```

To integrate web3swift into your Xcode project using CocoaPods, specify it in your `Podfile`:
But if you know chain ID upfront it's better to specify one as well as with chain ID, the initializer won't have to ask the RPC for it and thus you guarantee that the initializer completes successfully without any asynchronous calls, considering your URL using `http/s` scheme:
```swift
let optionalChainId: Networks = .Custom(networkID: 42)
try await Web3HttpProvider(url: rpcUrl, network: optionalChainId)
```

```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '13.0'
Specify a keystore manager for the Web3HttpProvider if you want `web3.personal` namespace to work as it relies on use of the keystore:
```swift
try await Web3HttpProvider(url: rpcUrl, network: optionalChainId, keystoreManager: optionalKeystoreManager)
```

target '<Your Target Name>' do
use_frameworks!
pod 'web3swift'
end
### Create Web3 Object
Creating a Web3 object is quite simple once you have a Web3 HTTP provider:
```swift
Web3(provider: provider)
```

Then, run the following command:
```bash
$ pod install
Or if you are a user of Infura:
```swift
try await Web3.InfuraMainnetWeb3(accessToken: optionalInfuraToken)
try await Web3.InfuraGoerliWeb3(accessToken: optionalInfuraToken)
```

> **WARNING**: CocoaPods is a powerful tool for managing dependencies in iOS development, but it also has some limitations that preventing us of providing first class support there. We highly recommend using SPM first as using CocoaPods will delay new updates and bug fixes being delivered to you.
If you have a URL or you are using Infura you can use the following:
```swift
try await Web3.new(url, network: chainIdHere)
// or
let web3 = try await Web3.InfuraMainnetWeb3(accessToken: optionalInfuraToken)
let web3 = try await Web3.InfuraGoerliWeb3(accessToken: optionalGoerliToken)
```

### Send Ether
```swift
Expand All @@ -129,7 +144,7 @@ web3.eth.send(transaction)
let contract = web3.contract(Web3.Utils.erc20ABI, at: receipt.contractAddress!)!
let readOp = contract.createReadOperation("name")!
readOp.transaction.from = EthereumAddress("0xe22b8979739D724343bd002F9f432F5990879901")
let response = try await readTX.callContractMethod()
let response = try await readTX.call()
```

### Write Transaction and call smart contract method
Expand All @@ -152,6 +167,7 @@ func feeHistory(blockCount: UInt, block: BlockNumber, percentiles:[Double]) asyn
return response.result
}
```

## Build from source
### SPM
```bash
Expand All @@ -166,7 +182,7 @@ swift build
- Swift 5.5

## Documentation
Documentation is under construction👷🏻👷🏼‍♀️. We’re trying our best to comment all public API as detailed as we can, but the end it still far to come. But in one of the nearest minor updates we’ll bring DocC support of already done amount of docs. And your PR in such are more than welcome.
Documentation is under construction👷🏻👷🏼‍♀️. We’re trying our best to comment on all public APIs as detailed as possible, but the end is still far to come. But in one of the nearest minor updates we’ll bring DocC support of already done amount of docs. And your PR in such are more than welcome.

## Projects that are using web3swift
Please take a look at [Our customers](https://github.com/web3swift-team/web3swift/wiki/Our-Customers) wiki page.
Expand All @@ -180,7 +196,7 @@ Please take a look at [Our customers](https://github.com/web3swift-team/web3swif
- If you **found a bug**, [open an issue](https://github.com/web3swift-team/web3swift/issues).

## Development
To do local development and run the local tests, we recommend to use [ganache](https://github.com/trufflesuite/ganache) which is also used by CI when running github actions.
To do local development and run the local tests, we recommend using [ganache](https://github.com/trufflesuite/ganache) which is also used by CI when running GitHub actions.

```cli
// To install
Expand All @@ -195,24 +211,24 @@ Make sure that `ganache` is running on its default port `8546`. To change the po

### Before you commit

We are using [pre-commit](https://pre-commit.com) to run validations locally before a commit is created. Please, install pre-commit and run `pre-commit install` from project's root directory. After that before every commit git hook will run and execute `codespell`, `swiftlint` and other checks.
We are using [pre-commit](https://pre-commit.com) to run validations locally before a commit is created. Please, install pre-commit and run `pre-commit install` from the project's root directory. After that before every commit git hook will run and execute `codespell`, `swiftlint` and other checks.

## Contribute
Want to improve? It's awesome:
Then good news for you: **We are ready to pay for your contribution via [@gitcoin bot](https://gitcoin.co/grants/358/web3swift)!**
The good news for you: **We are ready to pay for your contribution via [@gitcoin bot](https://gitcoin.co/grants/358/web3swift)!**

- If you **have a feature request**, [open an issue](https://github.com/web3swift-team/web3swift/issues).
- If you **want to contribute**, [submit a pull request](https://github.com/web3swift-team/web3swift/pulls).

### Contribution
1. You are more than welcome to participate and get bounty by contributing! **Your contribution will be paid via [@gitcoin Grant program](https://gitcoin.co/grants/358/web3swift).**
1. You are more than welcome to participate and get a bounty by contributing! **Your contribution will be paid via [@gitcoin Grant program](https://gitcoin.co/grants/358/web3swift).**
2. Find or create an [issue](https://github.com/web3swift-team/web3swift/issues)
3. You can find open bounties in [Gitcoin Bounties](https://gitcoin.co/explorer?applicants=ALL&keywords=web3swift&order_by=-web3_created) list
4. Commita fix or a new feature in branch, push your changes
4. Commita fix or a new feature in a branch, push your changes
5. [Submit a pull request to **develop** branch](https://github.com/web3swift-team/web3swift/pulls)
1. Please, provide detailed description to it to help us proceed it faster.
1. Please, provide a detailed description of it to help us proceed faster.

[@skywinder](https://github.com/skywinder) are charged with open-sourсe and do not require money for using web3swift library.
[@skywinder](https://github.com/skywinder) are charged with open-sourсe and do not require money to use the web3swift library.
We want to continue to do everything we can to move the needle forward.

- **Support us** via [@gitcoin Grant program](https://gitcoin.co/grants/358/web3swift)
Expand Down
69 changes: 62 additions & 7 deletions Sources/Web3Core/Contract/ContractProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,12 @@ public protocol ContractProtocol {
/// - name with arguments:`myFunction(uint256)`.
/// - method signature (with or without `0x` prefix, case insensitive): `0xFFffFFff`;
/// - data: non empty bytes to decode;
/// - Returns: dictionary with decoded values. `nil` if decoding failed.
func decodeReturnData(_ method: String, data: Data) -> [String: Any]?
/// - Returns: dictionary with decoded values.
/// - Throws:
/// - `Web3Error.revert(String, String?)` when function call aborted by `revert(string)` and `require(expression, string)`.
/// - `Web3Error.revertCustom(String, Dictionary)` when function call aborted by `revert CustomError()`.
@discardableResult
func decodeReturnData(_ method: String, data: Data) throws -> [String: Any]

/// Decode input arguments of a function.
/// - Parameters:
Expand Down Expand Up @@ -320,13 +324,40 @@ extension DefaultContractProtocol {
return bloom.test(topic: event.topic)
}

public func decodeReturnData(_ method: String, data: Data) -> [String: Any]? {
@discardableResult
public func decodeReturnData(_ method: String, data: Data) throws -> [String: Any] {
if method == "fallback" {
return [String: Any]()
return [:]
}

guard let function = methods[method]?.first else {
throw Web3Error.inputError(desc: "Make sure ABI you use contains '\(method)' method.")
}

switch data.count % 32 {
case 0:
return try function.decodeReturnData(data)
case 4:
let selector = data[0..<4]
if selector.toHexString() == "08c379a0", let reason = ABI.Element.EthError.decodeStringError(data[4...]) {
throw Web3Error.revert("revert(string)` or `require(expression, string)` was executed. reason: \(reason)", reason: reason)
}
else if selector.toHexString() == "4e487b71", let reason = ABI.Element.EthError.decodePanicError(data[4...]) {
let panicCode = String(format: "%02X", Int(reason)).addHexPrefix()
throw Web3Error.revert("Error: call revert exception; VM Exception while processing transaction: reverted with panic code \(panicCode)", reason: panicCode)
}
else if let customError = errors[selector.toHexString().addHexPrefix().lowercased()] {
if let errorArgs = customError.decodeEthError(data[4...]) {
throw Web3Error.revertCustom(customError.signature, errorArgs)
} else {
throw Web3Error.inputError(desc: "Signature matches \(customError.errorDeclaration) but failed to be decoded.")
}
} else {
throw Web3Error.inputError(desc: "Make sure ABI you use contains error that can match signature: 0x\(selector.toHexString())")
}
default:
throw Web3Error.inputError(desc: "Given data has invalid bytes count.")
}
return methods[method]?.compactMap({ function in
return function.decodeReturnData(data)
}).first
}

public func decodeInputData(_ method: String, data: Data) -> [String: Any]? {
Expand All @@ -346,8 +377,32 @@ extension DefaultContractProtocol {
return function.decodeInputData(Data(data[data.startIndex + 4 ..< data.startIndex + data.count]))
}

public func decodeEthError(_ data: Data) -> [String: Any]? {
guard data.count >= 4,
let err = errors.first(where: { $0.value.methodEncoding == data[0..<4] })?.value else {
return nil
}
return err.decodeEthError(data[4...])
}

public func getFunctionCalled(_ data: Data) -> ABI.Element.Function? {
guard data.count >= 4 else { return nil }
return methods[data[data.startIndex ..< data.startIndex + 4].toHexString().addHexPrefix()]?.first
}
}

extension DefaultContractProtocol {
@discardableResult
public func callStatic(_ method: String, parameters: [Any], provider: Web3Provider) async throws -> [String: Any] {
guard let address = address else {
throw Web3Error.inputError(desc: "RPC failed: contract is missing an address.")
}
guard let data = self.method(method, parameters: parameters, extraData: nil) else {
throw Web3Error.dataError
}
let transaction = CodableTransaction(to: address, data: data)

let result: Data = try await APIRequest.sendRequest(with: provider, for: .call(transaction, .latest)).result
return try decodeReturnData(method, data: result)
}
}
Loading
Loading