Skip to content

Commit

Permalink
feat: Add remaining examples (#83)
Browse files Browse the repository at this point in the history
  • Loading branch information
izik1 authored May 26, 2023
1 parent 50c409a commit 16e4d91
Show file tree
Hide file tree
Showing 19 changed files with 752 additions and 66 deletions.
5 changes: 3 additions & 2 deletions Examples/ConsensusPubSubChunked/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,10 @@ import Hedera
import HederaExampleUtilities
import SwiftDotenv

private let bigContents = HederaExampleUtilities.Resources.bigContents

@main
internal enum Program {
internal static func main() async throws {

let env = try Dotenv.load()
let client = try Client.forName(env.networkName)

Expand All @@ -50,6 +49,8 @@ internal enum Program {
try await Task.sleep(nanoseconds: 1_000_000_000 * 10)

_ = Task {
let bigContents = try await HederaExampleUtilities.Resources.bigContents

print(
"about to prepare a transaction to send a message of \(bigContents.count) bytes"
)
Expand Down
102 changes: 102 additions & 0 deletions Examples/CreateAccountThresholdKey/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
* ‌
* 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.
* ‍
*/

import Hedera
import SwiftDotenv

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

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

// Generate three new ed25519 private, public key pairs.
// You do not need the private keys to create the Threshold Key List,
// you only need the public keys, and if you're doing things correctly,
// you probably shouldn't have these private keys.
let privateKeys = [
PrivateKey.generateEd25519(),
PrivateKey.generateEd25519(),
PrivateKey.generateEd25519(),
]

print("public keys:")
for key in privateKeys {
print("\(key.publicKey)")
}

// require 2 of the 3 keys we generated to sign on anything modifying this account
let transactionKey = KeyList(
keys: privateKeys.map { .single($0.publicKey) },
threshold: 2
)

let transactionResponse = try await AccountCreateTransaction()
.key(.keyList(transactionKey))
.initialBalance(Hbar(10))
.execute(client)

// This will wait for the receipt to become available
let receipt = try await transactionResponse.getReceipt(client)

let newAccountId = receipt.accountId!

print("account = \(newAccountId)")

let transferTransactionResponse = try await TransferTransaction()
.hbarTransfer(newAccountId, Hbar(-10))
.hbarTransfer(AccountId(num: 3), Hbar(10))
// we sign with 2 of the 3 keys
.sign(privateKeys[0])
.sign(privateKeys[1])
.execute(client)

// (important!) wait for the transfer to go to consensus
_ = try await transferTransactionResponse.getReceipt(client)

let balanceAfter = try await AccountBalanceQuery()
.accountId(newAccountId)
.execute(client)
.hbars

print("account balance after transfer: \(balanceAfter)")
}
}

extension Environment {
/// Account ID for the operator to use in this example.
internal var operatorAccountId: AccountId {
AccountId(self["OPERATOR_ACCOUNT_ID"]!.stringValue)!
}

/// Private key for the operator to use in this example.
internal var operatorKey: PrivateKey {
PrivateKey(self["OPERATOR_KEY"]!.stringValue)!
}

/// The name of the hedera network this example should be ran against.
///
/// Testnet by default.
internal var networkName: String {
self["HEDERA_NETWORK"]?.stringValue ?? "testnet"
}
}
101 changes: 101 additions & 0 deletions Examples/CreateSimpleContract/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* ‌
* 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.
* ‍
*/

import Hedera
import HederaExampleUtilities
import SwiftDotenv

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

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

let bytecode = try await HederaExampleUtilities.Resources.simpleContract

// create the contract's bytecode file
let fileTransactionResponse = try await FileCreateTransaction()
// Use the same key as the operator to "own" this file
.keys([.single(env.operatorKey.publicKey)])
.contents(bytecode.data(using: .utf8)!)
.execute(client)

let fileReceipt = try await fileTransactionResponse.getReceipt(client)
let newFileId = fileReceipt.fileId!

print("contract bytecode file: \(newFileId)")

let contractTransactionResponse = try await ContractCreateTransaction()
.bytecodeFileId(newFileId)
.gas(500000)
.adminKey(.single(env.operatorKey.publicKey))
.constructorParameters(ContractFunctionParameters().addString("hello from hedera!"))
.execute(client)

let contractReceipt = try await contractTransactionResponse.getReceipt(client)
let newContractId = contractReceipt.contractId!

print("new contract ID: \(newContractId)")

let contractCallResult = try await ContractCallQuery()
.contractId(newContractId)
.gas(500000)
.function("greet")
.execute(client)

if let err = contractCallResult.errorMessage {
print("error calling contract: \(err)")
return
}

let message = contractCallResult.getString(0)
print("contract returned message: \(String(describing: message))")

// now delete the contract
_ = try await ContractDeleteTransaction()
.contractId(newContractId)
.transferAccountId(env.operatorAccountId)
.execute(client)
.getReceipt(client)

print("Contract successfully deleted")
}
}

extension Environment {
/// Account ID for the operator to use in this example.
internal var operatorAccountId: AccountId {
AccountId(self["OPERATOR_ACCOUNT_ID"]!.stringValue)!
}

/// Private key for the operator to use in this example.
internal var operatorKey: PrivateKey {
PrivateKey(self["OPERATOR_KEY"]!.stringValue)!
}

/// The name of the hedera network this example should be ran against.
///
/// Testnet by default.
internal var networkName: String {
self["HEDERA_NETWORK"]?.stringValue ?? "testnet"
}
}
118 changes: 118 additions & 0 deletions Examples/CreateStatefulContract/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* ‌
* 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.
* ‍
*/

import Hedera
import HederaExampleUtilities
import SwiftDotenv

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

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

let bytecode = try await HederaExampleUtilities.Resources.statefulContract

// create the contract's bytecode file
let fileTransactionResponse = try await FileCreateTransaction()
// Use the same key as the operator to "own" this file
.keys([.single(env.operatorKey.publicKey)])
.contents(bytecode.data(using: .utf8)!)
.execute(client)

let fileReceipt = try await fileTransactionResponse.getReceipt(client)
let newFileId = fileReceipt.fileId!

print("contract bytecode file: \(newFileId)")

let contractTransactionResponse = try await ContractCreateTransaction()
.bytecodeFileId(newFileId)
.gas(500000)
.constructorParameters(ContractFunctionParameters().addString("hello from hedera!"))
.execute(client)

let contractReceipt = try await contractTransactionResponse.getReceipt(client)
let newContractId = contractReceipt.contractId!

print("new contract ID: \(newContractId)")

let contractCallResult = try await ContractCallQuery()
.contractId(newContractId)
.gas(500000)
.function("get_message")
.execute(client)

if let err = contractCallResult.errorMessage {
print("error calling contract: \(err)")
return
}

let message = contractCallResult.getString(0)
print("contract returned message: \(String(describing: message))")

let contractExecTransactionResponse = try await ContractExecuteTransaction()
.contractId(newContractId)
.gas(500000)
.function(
"set_message",
ContractFunctionParameters().addString("hello from hedera again!")
)
.execute(client)

// if this doesn't throw then we know the contract executed successfully
_ = try await contractExecTransactionResponse.getReceipt(client)

// now query contract
let contractUpdateResult = try await ContractCallQuery()
.contractId(newContractId)
.gas(500000)
.function("get_message")
.execute(client)

if let err = contractUpdateResult.errorMessage {
print("error calling contract: \(err)")
return
}

let message2 = contractUpdateResult.getString(0)
print("contract returned message: \(String(describing: message2))")
}
}

extension Environment {
/// Account ID for the operator to use in this example.
internal var operatorAccountId: AccountId {
AccountId(self["OPERATOR_ACCOUNT_ID"]!.stringValue)!
}

/// Private key for the operator to use in this example.
internal var operatorKey: PrivateKey {
PrivateKey(self["OPERATOR_KEY"]!.stringValue)!
}

/// The name of the hedera network this example should be ran against.
///
/// Testnet by default.
internal var networkName: String {
self["HEDERA_NETWORK"]?.stringValue ?? "testnet"
}
}
4 changes: 1 addition & 3 deletions Examples/FileAppendChunked/main.swift
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import Foundation
import Hedera
import HederaExampleUtilities
import SwiftDotenv

private let bigContents = HederaExampleUtilities.Resources.bigContents

@main
internal enum Program {
internal static func main() async throws {
async let bigContents = HederaExampleUtilities.Resources.bigContents
let env = try Dotenv.load()
let client = try Client.forName(env.networkName)

Expand Down
Loading

0 comments on commit 16e4d91

Please sign in to comment.