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

[ADD] SwiftFormat #290

Merged
merged 2 commits into from
Dec 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 9 additions & 1 deletion .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@ on:
branches: [ develop ]

jobs:
lint:
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
- name: Lint
run: ./scripts/runSwiftFormat.sh -l
macos:
needs: lint
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
Expand All @@ -14,6 +21,7 @@ jobs:
- name: Tests
run: swift test -v
linux:
needs: lint
runs-on: ubuntu-latest
container:
image: swift:5.5-bionic
Expand All @@ -22,4 +30,4 @@ jobs:
- name: Build
run: swift build -v
- name: Tests
run: swift test -v
run: swift test -v
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,5 @@ fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output

scripts/bin/*
7 changes: 7 additions & 0 deletions scripts/prepareForPush.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/bin/sh

SWIFT_VERSION=5.3

cd "$(dirname "$0")"

./runSwiftFormat.sh
63 changes: 63 additions & 0 deletions scripts/runSwiftFormat.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#!/bin/sh

SWIFT_VERSION=5.3

cd "$(dirname "$0")"

function downloadAndUnzip {
curl -L -o tool.zip $2
unzip -o -d $1/ tool.zip
rm tool.zip
}

if ! which bin/swiftformat >/dev/null; then
echo "warning: SwiftFormat not installed, installing..."

mkdir -p -- "bin"
cd bin
rm -r ./*

downloadAndUnzip "SwiftFormatTmp" "https://github.com/nicklockwood/SwiftFormat/releases/download/0.50.3/swiftformat.artifactbundle.zip"
mv -f ./SwiftFormatTmp/swiftformat.artifactbundle/swiftformat-0.50.3-macos/bin/swiftformat .
find . -name "*Tmp" -type d -prune -exec rm -rf '{}' +
for entry in ./*
do
chmod +x "$entry"
done
cd ../
fi

cleanup() {
exit_code=$?
if [[ ${exit_code} -eq 0 ]]; then
exit 0
else
echo "Need to run scripts/prepareForPush.sh script to prepare the code before a PullRequest."
exit 1
fi
}

format() {
bin/swiftformat ../web3swift/src/ --config "swiftformat.yml" --swiftversion $SWIFT_VERSION
cleanup
}

lint() {
bin/swiftformat --lint ../web3swift/src/ --config "swiftformat.yml" --swiftversion $SWIFT_VERSION
cleanup
}

while getopts "fl" o; do
case "${o}" in
f)
format;
exit;;
l)
lint;
exit;;
*)
exit;;
esac
done

format
79 changes: 79 additions & 0 deletions scripts/swiftformat.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
--acronyms ID,URL,UUID
--allman false
--assetliterals visual-width
--beforemarks
--binarygrouping 4,8
--categorymark "MARK: %c"
--classthreshold 0
--closingparen balanced
--closurevoid remove
--commas always
--conflictmarkers reject
--decimalgrouping 3,6
--elseposition same-line
--emptybraces no-space
--enumnamespaces always
--enumthreshold 0
--exponentcase lowercase
--exponentgrouping disabled
--extensionacl on-extension
--extensionlength 0
--extensionmark "MARK: - %t + %c"
--fractiongrouping disabled
--fragment false
--funcattributes prev-line
--generictypes
--groupedextension "MARK: %c"
--guardelse same-line
--header ignore
--hexgrouping 4,8
--hexliteralcase uppercase
--ifdef indent
--importgrouping length
--indent 4
--indentcase false
--indentstrings false
--lifecycle
--lineaftermarks false
--linebreaks lf
--markcategories true
--markextensions always
--marktypes always
--maxwidth none
--modifierorder
--nevertrailing
--nospaceoperators
--nowrapoperators
--octalgrouping 4,8
--operatorfunc spaced
--organizetypes actor,class,enum,struct
--patternlet hoist
--ranges spaced
--redundanttype infer-locals-only
--self remove
--selfrequired
--semicolons inline
--shortoptionals always
--smarttabs enabled
--someAny true
--stripunusedargs always
--structthreshold 0
--tabwidth unspecified
--trailingclosures
--trimwhitespace always
--typeattributes prev-line
--typeblanklines remove
--typemark "MARK: - %t"
--varattributes same-line
--voidtype void
--wraparguments before-first
--wrapcollections before-first
--wrapconditions preserve
--wrapparameters before-first
--wrapreturntype preserve
--wrapternary default
--wraptypealiases preserve
--xcodeindentation disabled
--yodaswap always
--disable enumNamespaces,extensionAccessControl,fileHeader,genericExtensions,modifierOrder,numberFormatting,opaqueGenericParameters,preferKeyPath,redundantBackticks,redundantExtensionACL,redundantFileprivate,redundantPattern,redundantRawValues,redundantSelf,sortDeclarations,spaceAroundGenerics,strongOutlets,trailingClosures,trailingCommas,unusedArguments,wrap,wrapMultilineStatementBraces,wrapSingleLineComments,yodaConditions
--enable blankLineAfterImports,blankLinesBetweenImports,isEmpty,wrapConditionalBodies
6 changes: 2 additions & 4 deletions web3swift/src/Account/EthereumAccount+SignTransaction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ enum EthereumSignerError: Error {
}

public extension EthereumAccount {

func signRaw(_ transaction: EthereumTransaction) throws -> Data {
let signed: SignedTransaction = try sign(transaction: transaction)
guard let raw = signed.raw else {
Expand All @@ -21,7 +20,6 @@ public extension EthereumAccount {
}

func sign(transaction: EthereumTransaction) throws -> SignedTransaction {

guard let raw = transaction.raw else {
throw EthereumSignerError.emptyRawTransaction
}
Expand All @@ -30,8 +28,8 @@ public extension EthereumAccount {
throw EthereumSignerError.unknownError
}

let r = signature.subdata(in: 0..<32)
let s = signature.subdata(in: 32..<64)
let r = signature.subdata(in: 0 ..< 32)
let s = signature.subdata(in: 32 ..< 64)

var v = Int(signature[64])
if v < 37 {
Expand Down
40 changes: 16 additions & 24 deletions web3swift/src/Account/EthereumAccount.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
// Copyright © 2022 Argent Labs Limited. All rights reserved.
//

import Foundation
import Logging
import Foundation

public protocol EthereumAccountProtocol {
var address: EthereumAddress { get }
Expand All @@ -29,21 +29,17 @@ public class EthereumAccount: EthereumAccountProtocol {
private let publicKeyData: Data
private let logger: Logger

public lazy var publicKey: String = {
return self.publicKeyData.web3.hexString
}()
public lazy var publicKey: String = self.publicKeyData.web3.hexString

public lazy var address: EthereumAddress = {
return KeyUtil.generateAddress(from: self.publicKeyData)
}()
public lazy var address: EthereumAddress = KeyUtil.generateAddress(from: self.publicKeyData)

required public init(keyStorage: EthereumSingleKeyStorageProtocol, keystorePassword password: String, logger: Logger? = nil) throws {
self.logger = logger ?? Logger(label: "web3.swift.eth-account")
do {
let decodedKey = try keyStorage.loadAndDecryptPrivateKey(keystorePassword: password)
self.privateKeyData = decodedKey
self.publicKeyData = try KeyUtil.generatePublicKey(from: decodedKey)
} catch let error {
} catch {
self.logger.warning("Error loading key data: \(error)")
throw EthereumAccountError.loadAccountError
}
Expand All @@ -59,20 +55,20 @@ public class EthereumAccount: EthereumAccountProtocol {
throw EthereumAccountError.loadAccountError
}
}

required public init(addressString: String, keyStorage: EthereumMultipleKeyStorageProtocol, keystorePassword password: String, logger: Logger? = nil) throws {
self.logger = logger ?? Logger(label: "web3.swift.eth-account")
do {
let address = EthereumAddress(addressString)
let decodedKey = try keyStorage.loadAndDecryptPrivateKey(for: address, keystorePassword: password)
self.privateKeyData = decodedKey
self.publicKeyData = try KeyUtil.generatePublicKey(from: decodedKey)
} catch let error {
} catch {
self.logger.warning("Error loading key data: \(error)")
throw EthereumAccountError.loadAccountError
}
}

required public init(addressString: String, keyStorage: EthereumMultipleKeyStorageProtocol, logger: Logger? = nil) throws {
self.logger = logger ?? Logger(label: "web3.swift.eth-account")
do {
Expand All @@ -84,12 +80,12 @@ public class EthereumAccount: EthereumAccountProtocol {
throw EthereumAccountError.loadAccountError
}
}

public static func create(addingTo keyStorage: EthereumMultipleKeyStorageProtocol, keystorePassword password: String) throws -> EthereumAccount {
guard let privateKey = KeyUtil.generatePrivateKeyData() else {
throw EthereumAccountError.createAccountError
}

do {
try keyStorage.encryptAndStorePrivateKey(key: privateKey, keystorePassword: password)
let publicKey = try KeyUtil.generatePublicKey(from: privateKey)
Expand All @@ -99,7 +95,7 @@ public class EthereumAccount: EthereumAccountProtocol {
throw EthereumAccountError.createAccountError
}
}

public static func create(replacing keyStorage: EthereumSingleKeyStorageProtocol, keystorePassword password: String) throws -> EthereumAccount {
guard let privateKey = KeyUtil.generatePrivateKeyData() else {
throw EthereumAccountError.createAccountError
Expand All @@ -112,7 +108,7 @@ public class EthereumAccount: EthereumAccountProtocol {
throw EthereumAccountError.createAccountError
}
}

public static func importAccount(addingTo keyStorage: EthereumMultipleKeyStorageProtocol, privateKey: String, keystorePassword password: String) throws -> EthereumAccount {
guard let privateKey = privateKey.web3.hexData else {
throw EthereumAccountError.importAccountError
Expand All @@ -126,7 +122,7 @@ public class EthereumAccount: EthereumAccountProtocol {
throw EthereumAccountError.importAccountError
}
}

public static func importAccount(replacing keyStorage: EthereumSingleKeyStorageProtocol, privateKey: String, keystorePassword password: String) throws -> EthereumAccount {
guard let privateKey = privateKey.web3.hexData else {
throw EthereumAccountError.importAccountError
Expand All @@ -138,13 +134,13 @@ public class EthereumAccount: EthereumAccountProtocol {
throw EthereumAccountError.importAccountError
}
}

public func sign(data: Data) throws -> Data {
return try KeyUtil.sign(message: data, with: privateKeyData, hashing: true)
try KeyUtil.sign(message: data, with: privateKeyData, hashing: true)
}

public func sign(hex: String) throws -> Data {
if let data = Data.init(hex: hex) {
if let data = Data(hex: hex) {
return try KeyUtil.sign(message: data, with: privateKeyData, hashing: true)
} else {
throw EthereumAccountError.signError
Expand All @@ -160,7 +156,7 @@ public class EthereumAccount: EthereumAccountProtocol {
}

public func sign(message: Data) throws -> Data {
return try KeyUtil.sign(message: message, with: privateKeyData, hashing: false)
try KeyUtil.sign(message: message, with: privateKeyData, hashing: false)
}

public func sign(message: String) throws -> Data {
Expand All @@ -181,13 +177,11 @@ public class EthereumAccount: EthereumAccountProtocol {

guard var signed = try? sign(message: hash) else {
throw EthereumAccountError.signError

}

// Check last char (v)
guard var last = signed.popLast() else {
throw EthereumAccountError.signError

}

if last < 27 {
Expand All @@ -203,13 +197,11 @@ public class EthereumAccount: EthereumAccountProtocol {

guard var signed = try? sign(message: hash) else {
throw EthereumAccountError.signError

}

// Check last char (v)
guard var last = signed.popLast() else {
throw EthereumAccountError.signError

}

if last < 27 {
Expand Down
Loading