Phoenix Chain SDK Doc
  • Introduction
  • Client
    • Initializing a Client
  • Accounts
    • Querying Balances
  • Blocks and Transactions
    • Querying Blocks
    • Querying Transactions
  • Smart Contracts
    • Installing Dev Tools
    • Generating Go Contracts File
    • Deploying Contracts
    • Querying Contracts
    • Writing to Contracts
  • Event logs
    • Filtering Event logs
    • Subscribing to Event Logs
Powered by GitBook
On this page
  1. Smart Contracts

Writing to Contracts

To calling writing method of the contract, you need to provide the account private key for authentication.

package main
import (
	store "...The path of the store.go file..."
	"context"
	"crypto/ecdsa"
	"fmt"
	"log"
	"math/big"
	"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/accounts/abi/bind"
	"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/ethclient"
	"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/common"
	"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/crypto"
)
func main() {
	client, err := ethclient.Dial("https://dataseed1.phoenix.global/rpc")
	if err != nil {
		log.Fatal(err)
	}
	privateKey, err := crypto.HexToECDSA("your private key")
	if err != nil {
		log.Fatal(err)
	}
	publicKey := privateKey.Public()
	publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
	if !ok {
		log.Fatal("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
	}
	fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
	nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
	if err != nil {
		log.Fatal(err)
	}
	gasPrice, err := client.SuggestGasPrice(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	auth := bind.NewKeyedTransactor(privateKey)
	auth.Nonce = big.NewInt(int64(nonce))
	auth.Value = big.NewInt(0)
	auth.GasLimit = uint64(300000)
	auth.GasPrice = gasPrice
	contractAddress := common.HexToAddress("0x9aC8B849A8b6Fc14F8dEcfa6A22dB41671B38eFB")
	instance, err := store.NewStore(contractAddress, client)
	if err != nil {
		log.Fatal(err)
	}
	key := [32]byte{}
	value := [32]byte{}
	copy(key[:], []byte("storeKey"))
	copy(value[:], []byte("storeValue"))
	// calling the writing method
	tx, err := instance.SetItem(auth, key, value)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("transaction hash:", tx.Hash().Hex())
	result, err := instance.Items(nil, key)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(result[:])) // "storeValue"
}
PreviousQuerying ContractsNextEvent logs

Last updated 2 years ago