Code Monkey home page Code Monkey logo

hedera-sdk-swift's Introduction

Hedera™ Swift SDK

The SDK for interacting with Hedera Hashgraph: the official distributed consensus platform built using the hashgraph consensus algorithm for fast, fair and secure transactions. Hedera enables and empowers developers to build an entirely new class of decentralized applications.

Maintained with ❤️ by LaunchBadge, Swirlds Labs, and the Hedera community

Requirements

  • Swift v5.6+
  • MacOS v10.15+ (2019, Catalina)
  • iOS 13+ (2019)

Install

// Package.swift
dependencies: [
    .package(url: "https://github.com/hashgraph/hedera-sdk-swift.git", from: "0.1.0")
]

See "Adding Package Dependencies to Your App" for help on adding a swift package to an Xcode project.

Usage

import Hedera

// connect to the Hedera network
let client = Client.forTestnet()

// query the balance of an account
let ab = try await AccountBalanceQuery()
    .accountId(AccountId("0.0.1001")!)
    .execute(client)

print("balance = \(ab.balance)")

See examples for more usage.

Community and Support

If you have any questions on the Hedera SDK or Hedera more generally, you can join our team and hundreds of other developers using Hedera in our community Discord:

License

Licensed under Apache License, Version 2.0 – see LICENSE or apache.org/licenses/LICENSE-2.0.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions.

Development (HederaProtobufs)

HederaProtobufs is entirely generated

Required tooling

protoc protoc-gen-swift (from https://github.com/apple/swift-protobuf) protoc-gen-grpc-swift (from https://github.com/grpc/grpc-swift)

Generate services

# cwd: `$REPO`
protoc --swift_opt=Visibility=Public  --swift_opt=FileNaming=PathToUnderscores --swift_out=./Sources/HederaProtobufs/Services --proto_path=./protobufs/services protobufs/services/**.proto

# generate GRPC (if needed)
protoc --grpc-swift_opt=Visibility=Public,Server=false --grpc-swift_out=./Sources/HederaProtobufs/Services --proto_path=protobufs/services protobufs/services/**.proto

Generate Mirror

# cwd: `$REPO/sdk/swift`
protoc --swift_opt=Visibility=Public --swift_opt=FileNaming=PathToUnderscores --swift_out=./Sources/HederaProtobufs/Mirror -I=protobufs/mirror -I=protobufs/services protobufs/mirror/**.proto

# generate GRPC (if needed)
protoc --grpc-swift_opt=Visibility=Public,FileNaming=PathToUnderscores,Server=false --grpc-swift_out=./Sources/HederaProtobufs/Mirror -I=protobufs/mirror -I=protobufs/services protobufs/mirror/**.proto

Integration Tests

Before running the integration tests, an operator key, operator account id, and a network name must be set in an .env file.

# Account that will pay query and transaction fees
TEST_OPERATOR_ID=
# Default private key to use to sign for all transactions and queries
TEST_OPERATOR_KEY=
# Network names: `"localhost"`, `"testnet"`, `"previewnet"`, `"mainnet"`
TEST_NETWORK_NAME=
# Run tests
$  swift test 

Local Environment Testing

Hedera offers a way to run tests through your localhost using the hedera-local-node service.

For instructions on how to set up and run local node, follow the steps in the git repository: https://github.com/hashgraph/hedera-local-node

Once the local node is running in Docker, the appropriate .env values must be set:

TEST_OPERATOR_ID=0.0.2
TEST_OPERATOR_KEY=3030020100300706052b8104000a042204205bc004059ffa2943965d306f2c44d266255318b3775bacfec42a77ca83e998f2
TEST_NETWORK_NAME=localhost

Lastly, run the tests using swift test

Generate SDK

# cwd: `$REPO/sdk/swift`
protoc --swift_opt=Visibility=Public --swift_opt=FileNaming=PathToUnderscores --swift_out=./Sources/HederaProtobufs/Sdk -I=protobufs/sdk -I=protobufs/services protobufs/sdk/**.proto

hedera-sdk-swift's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hedera-sdk-swift's Issues

Swift tools version specification is missing

Description

Xcode reports when trying to build:

the Swift tools version specification is missing a label; consider inserting 'swift-tools-version:' between the comment marker and the version specifier

In Package.swift, the following line should be moved a the top (before source code header):

// swift-tools-version:5.5

Steps to reproduce

  1. Clone [email protected]:hashgraph/hedera-sdk-swift.git
  2. Open hedera-sdk-swift with Xcode 13.4.1
  3. Build
    => build fails with the following message:

the Swift tools version specification is missing a label; consider inserting 'swift-tools-version:' between the comment marker and the version specifier

Additional context

No response

Hedera network

testnet

Version

0.5.0

Operating system

macOS

memo field does not exist for Transaction

Description

TransferTransaction doesn't have a function for setting memo.

Steps to reproduce

Try to write code as below additional context with memo.

Additional context

let response = try await TransferTransaction()
                    .hbarTransfer(AccountId.fromString(coinWallet.getWalletAddress()), sendAmount * -1)
                    .hbarTransfer(AccountId.fromString(toAddress), sendAmount)
                    .memo("memo test") // <- cannot set memo for now
                    .execute(client)

Hedera network

mainnet

Version

0.14.0

Operating system

macOS

Unable to get info for Schedule ID

Description

When tried to fetch schedule info on testnet got below response
query with no payment transaction failed pre-check with status InvalidScheduleId

Steps to reproduce

let info = try await ScheduleInfoQuery() .scheduleId(scheduleID) .execute(client)

Additional context

No response

Hedera network

testnet

Version

v0.15.0

Operating system

macOS

Cannot compile due to unsafe build flag

Description

With sdk v0.16.0, there is a problem when compiling.

It always returns following error message.
"the target 'Hedera' in product 'Hedera' contains unsafe build flags."

Screenshot 2023-04-10 at 2 36 52 PM

Steps to reproduce

XCode 14.2

  1. Import Hedera swift sdk ver 0.16.0 on my package.
  2. Try to build with it.

Additional context

.package(name: "hedera-sdk-swift", url: "https://github.com/hashgraph/hedera-sdk-swift.git", .exact("0.16.0")),

Hedera network

mainnet

Version

v0.16.0

Operating system

macOS

TODO comment left in `AccountCreateTransaction`

Need fromBytes method for Transaction

Problem

Serialized Transaction cannot be decoded with hedera-sdk-swift.

Hedera official sdks for Java and Go have fromBytes() API so user can decode serialized transaction.

Solution

Add fromBytes() API for Transaction classes.

Alternatives

No response

'NumberKit' requires minimum platform version 12.0

Description

The following error occurred when adding the sdk to a simple project

The package product 'NumberKit' requires minimum platform version 12.0 for the iOS platform, but this target supports 9.0

Steps to reproduce

created a simple iOS project
added Hedera package
Clicked run

Additional context

No response

Hedera network

testnet

Version

beta

Operating system

No response

'NumberKit' requires minimum platform version 12.0 for the iOS platform

Description

When I tried to link hedera-sdk-swift package to my sample iOS project, I get this error:

The package product 'NumberKit' requires minimum platform version 12.0 for the iOS platform, but this target supports 9.0

If I uncomment iOS platform in Package.swift, error above disappears:

let package = Package(
    name: "Hedera",
    platforms: [
        .macOS(.v10_15)
        // .iOS(.v12),           <=== HERE
    ],
    …
)

Now I get the error reported in #22 (this one is closed but issue still exists).

Steps to reproduce

  1. Start Xcode
  2. File > New > Project > iOS > App
    Product Name: XXX

    Language: Swift
  3. File > Add Packages
  4. hedera-sdk-swift in Search Field + Add Package
  5. Product > Build
    => build breaks ; see build output below
Prepare build
...
Build target Hedera with configuration Debug
error: The package product 'NumberKit' requires minimum platform version 12.0 for the iOS platform, but this target supports 9.0 (in target 'Hedera' from project 'Hedera')
error: Both 'macos-arm64' and 'macos-x86_64' represent two equivalent library definitions. (in target 'Hedera' from project 'Hedera')
...
Build failed    13/09/2022 23:29    0.1 seconds

Additional context

Build XXX_2022-09-13T23-29-18.txt

Hedera network

other

Version

0.6.0

Operating system

macOS

Unable to create NFT with Custom Fee

Description

When I tried to create NFT with Custom fee with no denomination token id then I receive below error
failed to parse a request from JSON: missing field denominatingTokenId at line 1 column 951

But when I added any random token id then transaction execution was successful

Steps to reproduce

When I tried using below custom fee I got the error

let fixedFee = FixedFee(amount: 1000, denominatingTokenId: nil, feeCollectorAccountId: collectorID, allCollectorsAreExempt: true)
let fallbackFee = FixedFee(amount: 200, denominatingTokenId: nil, feeCollectorAccountId: collectorID, allCollectorsAreExempt: true)
let royaltyFee = RoyaltyFee(numerator: 1, denominator: 50, fallbackFee: fallbackFee, feeCollectorAccountId: collectorID, allCollectorsAreExempt: true)

Additional context

No response

Hedera network

testnet

Version

v0.14.0

Operating system

macOS

`AccountUpdateTransaction` failed to update staked node id

Description

The statement:

let transactionResponse = try await AccountUpdateTransaction()
            .accountId(env.operatorAccountId)
            .stakedNodeId(nodeId)
            .execute(client)

raises the following error:

Swift/ErrorType.swift:200: Fatal error: Error raised at top level: failed to parse a request from JSON: data did not match any variant of untagged enum AnyRequest

Steps to reproduce

Run sample program below:

import Foundation
import Hedera
import SwiftDotenv

@main
public enum Program {
    public static func main() async throws {
        let env = try Dotenv.load()
        let client = Client.forTestnet()

        client.setOperator(env.operatorAccountId, env.operatorKey)

        let nodeId = UInt64(1)
        let transactionResponse = try await AccountUpdateTransaction()
            .accountId(env.operatorAccountId)
            .stakedNodeId(nodeId)
            .execute(client)
        
        print("\( env.operatorAccountId ) is now staking to node \( nodeId )")

        // either of these values can be used to lookup transactions in an explorer such as
        //  Kabuto or DragonGlass; the transaction ID is generally more useful as it also contains a rough
        //  estimation of when the transaction was created (+/- 8 seconds) and the account that paid for
        //  transaction
        print("transaction id: \(transactionResponse.transactionId)")
        print("transaction hash: \(transactionResponse.transactionHash)")
    }
}

extension Environment {
    internal var operatorAccountId: AccountId {
        AccountId(self["OPERATOR_ACCOUNT_ID"]!.stringValue)!
    }

    internal var operatorKey: PrivateKey {
        PrivateKey(self["OPERATOR_KEY"]!.stringValue)!
    }
}

Additional context

No response

Hedera network

testnet

Version

0.11.0

Operating system

macOS

TransferTransaction throw protocol error but completes anyway

Description

I run a TransferTransaction on mainnet which thrown the following error:

grpc: status: Internal, message: "protocol error: received message with invalid compression flag: 60 (valid flags are 0 and 1) while receiving response with status: 503 Service Unavailable", details: [], metadata: MetadataMap { headers: {"content-length": "107" "cache-control": "no-cache" "content-type": "text/htm|"} }

However transaction completed successfully on mainnet (status == .success)

Steps to reproduce

Here is the code I used:

                // 1) Executes transaction
                let client = controller.model.network.makeClient()
                client.setOperator(payerAccountId!, payerKey!)
                response = try await TransferTransaction()
                      .hbarTransfer(sourceAccount, -tbarAmount)
                      .hbarTransfer(targetAccountId!, +tbarAmount)
                      .execute(client)
               
                // 2) Waits for receipt
                receipt = try await response!.getReceipt(client)

Additional context

No response

Hedera network

mainnet

Version

v0.13.0

Operating system

macOS

CreateAccountExample fails on `mainnet` with status `InvalidSignature`

Description

Example CreateAccount works fine on previewnet and testnet but fails on mainnet.
The following output is printed by the example:

Swift/ErrorType.swift:200: Fatal error: Error raised at top level: transaction `[email protected]` failed pre-check with status `InvalidSignature`
2023-02-14 00:14:52.256990+0100 CreateAccountExample[23301:271003] Swift/ErrorType.swift:200: Fatal error: Error raised at top level: transaction `[email protected]` failed pre-check with status `InvalidSignature`

Steps to reproduce

  1. Setup OPERATOR_ACCOUNT_ID and OPERATOR_KEY with a mainnet account
  2. Run Examples/CreateAccount/main.swift
    => creation aborts and prints output described above.

Additional context

No response

Hedera network

mainnet

Version

v0.12.0

Operating system

macOS

Build Failure

Description

What Happend

  • Build but I have some compile errors.

Expected Result

  • Build complete without any compile error.

Steps to reproduce

  • cloned the repository with version 0.7.0
  • Build with XCode. (I am using Xcode v 13.4.1 and MacBook Pro M1 with OSX v12.2.1(Monterey).
    p01
    p03
    p02

Additional context

No response

Hedera network

testnet

Version

0.7.0

Operating system

macOS

Cannot get precheck code for error case

Description

After execute transaction, I cannot get precheck code from HError for error cases.

Steps to reproduce

Here is an example code with HederaPrecheckStatusError but HederaPrecheckStatusError is not defined in the sdk yet.

do {
    let response = try await TransferTransaction()
        .tokenTransfer(tokenId, accountId1, -10)
        .tokenTransfer(tokenId, accountId2, 10)
        .freezeWith(client)
        .sign(privateKey1)
        .execute(client)
        .getReceipt(client)
} catch let error as HError {
    if let precheckError = error as? HederaPrecheckStatusError { // Cannot use HederaPrecheckStatusError
        // Handle precheck status errors
        let status = precheckError.status
        switch status {
        case .invalidAccountId:
            print("Invalid Account ID")
        case .tokenNotAssociatedToAccount:
            print("Token not associated to account")
        // Add other cases as needed
        default:
            print("Other precheck status error")
        }
    } else {
        // Handle other error cases
        print("Other error: \(error)")
    }
}

Additional context

No response

Hedera network

mainnet

Version

0.15.0

Operating system

macOS

Cannot initialize PrivateKey object from string

Description

Cannot initialise private key from PrivateKey constructor when passing private key from string created using Hashpack or Blade Wallet.

However, it's working fine when using private key that has been generated using PrivateKey generate methods.

Steps to reproduce

  1. Create a testnet wallet using Hashpack or Blade Wallet
  2. Reveal the wallet private key
  3. Use the wallet private key string in PrivateKey(stringLiteral:) constructor

Additional context

Using my testnet private key:
let pkString = "302e..."
let pkInstance = PrivateKey(stringLiteral: pkString)
The application throws an exception in PrivateKey.swift file at line 25:
if err != HEDERA_ERROR_OK { return nil }
where
err = [.HEDERA_ERROR_GRPC_STATUS, .HEDERA_ERROR_QUERY_NO_PAYMENT_PRE_CHECK_STATUS]

Hedera network

testnet

Version

v.0.6.0

Operating system

macOS

Problem with getting accountId checksum

Description

What happened

Cannot get checksum for account id and the following error occurred.
image
image

What Expected

It should return checksum address for given accout.

Steps to reproduce

  1. Import Hedera swift sdk with Package manager.

  2. Run unit test with following codes.

func testAccountChecksumTest() throws {
    let checksumed = AccountId("0.0.1126123").toStringWithChecksum(.forMainnet())
    print("hedera checksum=\(checksumed)")
}

Additional context

I tried following codes in hedera-sdk-swift with EntityIdTests.swift, which is almost same as above codes.

internal func testAccountIdChecksum() {
    let checksumAddress = AccountId("0.0.1126123").toStringWithChecksum(.forMainnet())
    print("testAccountIdChecksum(): checksumed=\(checksumAddress)")
}

By the way, it always returns values for Testnet.
image

I wonder if I tried right approach for getting account checksum.

Hedera network

mainnet

Version

v0.13.0

Operating system

macOS

Add license headers

Add license headers to the source code files.

/*
 * ‌
 * Hedera Swift SDK
 * ​
 * Copyright (C) 2022 - 2023 Hedera Hashgraph, LLC
 * ​
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ‍
 */

Changing staking with AccountUpdateTransaction terminates with ACCOUNT_ID_DOES_NOT_EXIST error

Description

With #33 fixed, the statement:

let transactionResponse = try await AccountUpdateTransaction()
            .accountId(env.operatorAccountId)
            .stakedNodeId(nodeId)
            .execute(client)

now no longer throws any exception but completes with ACCOUNT_ID_DOES_NOT_EXIST error.

See the two attempts below:

https://hashscan.io/testnet/transaction/1676027561.402742200?tid=0.0.1257-1676027555-549955227
https://hashscan.io/testnet/transaction/1676027835.568242649?tid=0.0.1257-1676027828-209408628

Steps to reproduce

See #33.

Additional context

No response

Hedera network

testnet

Version

0.12.0

Operating system

macOS

Transfer transaction methods do not match the naming convention

Swift:

- hbarTransfer(_ accountId: AccountId, _ amount: Int64)
- approvedHbarTransfer(_ accountId: AccountId, _ amount: Int64)
- tokenTransfer(_ tokenId: TokenId, _ accountId: AccountId, _ amount: Int64)
- approvedTokenTransfer(_ tokenId: TokenId, _ accountId: AccountId, _ amount: Int64)
- tokenTransferWithDecimals( _ tokenId: TokenId, _ accountId: AccountId, _ amount: Int64, _ expectedDecimals: UInt32 )
- approvedTokenTransferWithDecimals(  _ tokenId: TokenId, _ accountId: AccountId, _ amount: Int64, _ expectedDecimals: UInt32 )
- nftTransfer(_ nftId: NftId, _ senderAccountId: AccountId, _ receiverAccountId: AccountId)
- approvedNftTransfer( _ nftId: NftId, _ senderAccountId: AccountId, _ receiverAccountId: AccountId)

Java:

- addTokenTransfer(TokenId tokenId, AccountId accountId, long value)
- addApprovedTokenTransfer(TokenId tokenId, AccountId accountId, long value)
- addTokenTransferWithDecimals()
- addApprovedTokenTransferWithDecimals()
- doAddNftTransfer()
- addNftTransfer()
- addApprovedNftTransfer()
- doAddHbarTransfer()
- addHbarTransfer()
- addApprovedHbarTransfer()

Please update the naming convention for Swift.

Different AccountId Exception Handling from hedera-java-sdk

Description

What happened.

Same AccountId.fromString() functions on between Java SDK and Swift SDK acts different for wrong format address string.

Expected result

In swift sdk, AccountId.fromString() with wrong format address string should throw a proper exception like the one in java sdk.

Steps to reproduce

Following Java code makes IllegalArgumentException

String address = "0.00.12345"; // wrong format
try {
    AccountId accountId = AccountId.fromString(address); // IllegalArgumentException occurred.
} catch (IllegalArgumentException e) {
    //....
}

By the way,
Following swift code does not make any exception but returns fixed account address

let address = " 0.00.12345" // wrong format
let validAddress = try AccountId.fromString(address) // No exception occurred.
print(validAddress) // "0.0.12345"

Additional context

No response

Hedera network

mainnet

Version

v0.15.0

Operating system

macOS

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.