maptuhec
maptuhec

Reputation: 102

Interacting with custom smart contract using web3swift

I am using the web3swift library and I managed to do some transactions, mostly gets (balanceOf, owner etc). I read the whole readme(documentation), but I am not quite sure, can we use this library to call functions from our custom smart contracts? For example I have store smart contract and I want to call the buy function from it? I saw that we can transfer eth and ERC20 tokens but that is not enough for me. Any help on this?

Upvotes: 3

Views: 1224

Answers (1)

Georgy Fesenko
Georgy Fesenko

Reputation: 76

Yes, you can call any function on your custom smart contract. Here is an example.

        let infura = Web3.InfuraMainnetWeb3()
        // 1
        let contract = infura.contract(someABI, at: ethContractAddress, abiVersion: 2)
        // 2
        var options = Web3Options.defaultOptions()
        options.from = address
        // 3 
        let transactionIntermediate = contract?.method("accountExists", parameters:[address] as [AnyObject], options: options)
        // 4
        let result = transactionIntermediate!.call(options: options)
        switch result {
        // 5    
        case .success(let res):
            let ans = res["0"] as! Bool
            DispatchQueue.main.async {
                completion(Result.Success(ans))
            }
        case .failure(let error):
            DispatchQueue.main.async {
                completion(Result.Error(error))
            }
        }
    }  
  1. Setting up the contract and ABI. You need contract address for this in Data or String format. let ethContractAddress = EthereumAddress("0xfa28eC7198028438514b49a3CF353BcA5541ce1d")! You can get the ABI of your contract directly from Remix IDE.
  2. Set up all the options you want.
  3. Probably one of the main parts of the answer - here you create the transaction with contract method name and put into it all the parameters this method needs. 4.Here you can either call or send the transaction. call method is for methods with view identifier in solidity, so you won't pay for it and method send() is for the methods of smart contract that should be paid with gas for execution.
  4. Here you just parse the result, returned by the method. You should know data types of the variables you want to obtain from the concrete method in order to parse them correctly.

I hope my answer will help you! If something is still unclear - feel free to ask! :)

Upvotes: 3

Related Questions