cedra

package module
v0.0.0-...-e321bb2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

README

cedra-go-tx-pablisher

A Golang library was developed from scratch to enable transaction publishing.

Documentation

Overview

Package cedra provides a Go library for creating and submitting transactions to the Cedra blockchain. It supports account management, transaction creation, signing, and submission to Cedra network nodes.

Index

Constants

View Source
const (

	// CedraAddress is the canonical address of the Cedra system.
	CedraAddress = "0x0000000000000000000000000000000000000000000000000000000000000001"
	// CedraCoin is the native Cedra fee identity (address::symbol).
	CedraCoin = CedraAddress + "::Cedra"
)

Variables

View Source
var CedraChains = ChainConfig{
	DevnetChainID: {
		ChainID:      DevnetChainID,
		CedraNodeUrl: "https://devnet.cedra.dev/v1/",
	},
	TestnetChainID: {
		ChainID:      TestnetChainID,
		CedraNodeUrl: "https://testnet.cedra.dev/v1/",
	},
	MainnetChainID: {
		ChainID:      MainnetChainID,
		CedraNodeUrl: "https://mainnet.cedra.dev/v1/",
	},
}

CedraChains contains the predefined chain configurations for devnet, testnet, and mainnet.

Functions

func EncodeIntToBCS

func EncodeIntToBCS[Type int8 | int16 | int32 | int64](value Type) []byte

EncodeIntToBCS encodes a signed integer to BCS format using big-endian byte order. Supports int8, int16, int32, and int64 types. Panics if an unsupported type is provided.

func EncodeToBCSBytes

func EncodeToBCSBytes(data []byte) []byte

EncodeToBCSBytes encodes a byte slice to BCS format with length prefix. This is a convenience function that creates a new encoder, encodes the data, and returns the result.

func EncodeToBCSString

func EncodeToBCSString(value string) []byte

EncodeToBCSString encodes a string to BCS format with length prefix. This is a convenience function that creates a new encoder, encodes the string, and returns the result.

func EncodeUintToBCS

func EncodeUintToBCS[Type uint8 | uint16 | uint32 | uint64](value Type) []byte

EncodeUintToBCS encodes an unsigned integer to BCS format using little-endian byte order. Supports uint8, uint16, uint32, and uint64 types. Panics if an unsupported type is provided.

func EncodeVectorU8

func EncodeVectorU8(value []byte) []byte

func EncodeVectorU64

func EncodeVectorU64(values []uint64) []byte

func EncodeVectorVectorU8

func EncodeVectorVectorU8(values [][]byte) []byte

func NewAccountAddress

func NewAccountAddress(address string) ([32]byte, error)

NewAccountAddress parses a hexadecimal address string and returns a 32-byte address. The address can optionally include the "0x" prefix. Returns an error if the address format is invalid or exceeds 32 bytes.

func NewResourceAccount

func NewResourceAccount(accountAddress [32]byte, seed []byte) ([32]byte, error)

Types

type Account

type Account struct {
	// AccountAddress is the 32-byte account address derived from the public key.
	AccountAddress [32]byte
	// PrivateKey is the ED25519 private key used for signing transactions.
	PrivateKey ed25519.PrivateKey
	// PublicKey is the ED25519 public key associated with the account.
	PublicKey ed25519.PublicKey
}

Account represents a Cedra blockchain account with its cryptographic keys and address.

func NewAccount

func NewAccount(hexKey string) (Account, error)

NewAccount creates a new Account from a hexadecimal private key string. The hexKey can optionally include the "ed25519-priv-" prefix and/or "0x" prefix. Returns an error if the key format is invalid or cannot be parsed.

func (Account) GetAccountAddressString

func (a Account) GetAccountAddressString() string

GetAccountAddressString returns the hexadecimal string representation of the account address.

type AccountDTO

type AccountDTO struct {
	// SequenceNumber is the current sequence number of the account.
	SequenceNumber string `json:"sequence_number"`
	// AuthenticationKey is the authentication key for the account.
	AuthenticationKey string `json:"authentication_key"`
}

AccountDTO represents the account information returned from the Cedra node API.

type BCSEncoder

type BCSEncoder struct {
	// contains filtered or unexported fields
}

BCSEncoder provides Binary Canonical Serialization (BCS) encoding functionality. BCS is a deterministic serialization format used by the Cedra blockchain.

func NewBCSEncoder

func NewBCSEncoder() *BCSEncoder

NewBCSEncoder creates a new BCS encoder instance.

func (*BCSEncoder) EncodeBytes

func (bcs *BCSEncoder) EncodeBytes(data []byte)

EncodeBytes encodes a byte slice with its length prefix. The length is encoded as a ULEB128-encoded uint64, followed by the bytes.

func (*BCSEncoder) EncodeEnum

func (bcs *BCSEncoder) EncodeEnum(value uint64)

EncodeEnum encodes a uint64 value using variable-length encoding (ULEB128). This is used for encoding enum variants and length values.

func (*BCSEncoder) EncodeString

func (bcs *BCSEncoder) EncodeString(value string)

EncodeString encodes a string value with its length prefix. The length is encoded as a ULEB128-encoded uint64, followed by the string bytes.

func (*BCSEncoder) GetBytes

func (bcs *BCSEncoder) GetBytes() []byte

GetBytes returns a copy of the encoded bytes from the buffer.

func (*BCSEncoder) GetMessageLen

func (bcs *BCSEncoder) GetMessageLen() int

GetMessageLen returns the current length of the encoded message in bytes.

func (*BCSEncoder) Reset

func (bcs *BCSEncoder) Reset()

Reset clears the encoder buffer, allowing it to be reused.

func (*BCSEncoder) SetMessageLen

func (bcs *BCSEncoder) SetMessageLen(msgLen uint8)

SetMessageLen prepends a message length prefix to the encoded buffer. This is useful for encoding messages that need a length header.

func (*BCSEncoder) WriteI32

func (bcs *BCSEncoder) WriteI32(value int32)

func (*BCSEncoder) WriteI64

func (bcs *BCSEncoder) WriteI64(value int64)

func (*BCSEncoder) WriteRawByte

func (bcs *BCSEncoder) WriteRawByte(b byte)

WriteRawByte...

func (*BCSEncoder) WriteRawBytes

func (bcs *BCSEncoder) WriteRawBytes(value []byte)

WriteRawBytes appends raw bytes to the encoder buffer without any length prefix.

func (*BCSEncoder) WriteU16

func (bcs *BCSEncoder) WriteU16(value uint16)

func (*BCSEncoder) WriteU32FromInt

func (bcs *BCSEncoder) WriteU32FromInt(value int)

func (*BCSEncoder) WriteU32FromUint32

func (bcs *BCSEncoder) WriteU32FromUint32(value uint32)

func (*BCSEncoder) WriteU32FromUint64

func (bcs *BCSEncoder) WriteU32FromUint64(value uint64)

func (*BCSEncoder) WriteU64

func (bcs *BCSEncoder) WriteU64(value uint64)

type CedraAuthenticator

type CedraAuthenticator struct {
	// Variant specifies the transaction variant type.
	Variant uint64
	// Auth contains the sender authentication data (public key and signature).
	Auth SenderAuth
}

CedraAuthenticator represents the authentication information for a Cedra transaction.

func NewCedraAuthenticator

func NewCedraAuthenticator(pKey []byte, signature []byte) CedraAuthenticator

NewCedraAuthenticator creates a new CedraAuthenticator with the provided public key and signature.

func (CedraAuthenticator) EncodeBSC

func (a CedraAuthenticator) EncodeBSC() []byte

EncodeBSC encodes the authenticator into Binary Canonical Serialization (BCS) format. Returns the serialized byte representation of the authenticator.

type CedraClient

type CedraClient struct {
	// contains filtered or unexported fields
}

CedraClient is the main client for interacting with the Cedra blockchain. It provides methods for creating and submitting transactions.

func NewCedraClient

func NewCedraClient(chainID ChainID) CedraClient

NewCedraClient creates a new CedraClient instance for the specified chain.

func (CedraClient) GetSequenceNumber

func (c CedraClient) GetSequenceNumber(address string) (uint64, error)

GetSequenceNumber retrieves the current sequence number for the specified account address. Returns the sequence number as a uint64, or an error if the request fails.

func (CedraClient) IsTxExecuted

func (c CedraClient) IsTxExecuted(ctx context.Context, txHash string) (bool, error)

IsTxExecuted checks if a transaction has been successfully executed on the blockchain. It polls the node at regular intervals (100ms) until the transaction is executed or a timeout occurs (15 seconds). The context can be used to cancel the operation or extend the timeout. Returns true if the transaction has been executed successfully, false if it times out, or an error if the check fails.

func (CedraClient) NewTransaction

func (c CedraClient) NewTransaction(sender Account, payload *TransactionPayload, options ...any) (*Transaction, error)

NewTransaction creates a new transaction with the provided sender and payload. It concurrently fetches the sequence number and gas price estimate from the network if not provided via options. The transaction expiration is set to 5 minutes from creation time. Options can include SequenceNumber and GasUnitPrice to skip network calls. Returns an error if the sequence number cannot be fetched or if the struct tag is invalid.

func (CedraClient) SubmitTransaction

func (c CedraClient) SubmitTransaction(tx []byte, auth CedraAuthenticator) (string, error)

SubmitTransaction submits a signed transaction to the Cedra network. The transaction bytes and authenticator are combined and sent to the node. Returns the transaction hash if successful, or an error if submission fails.

type CedraNode

type CedraNode struct {
	// contains filtered or unexported fields
}

CedraNode represents a client for communicating with a Cedra blockchain node.

func NewCedraNode

func NewCedraNode(chainID ChainID) CedraNode

NewCedraNode creates a new CedraNode instance for the specified chain. Panics if the chain configuration is invalid or the chain ID doesn't exist.

func (CedraNode) GetEstimateGasPrice

func (n CedraNode) GetEstimateGasPrice() (EstimateGasPriceDTO, error)

GetEstimateGasPrice retrieves the current gas price estimates from the Cedra node. Returns gas price estimates for different priority levels.

func (CedraNode) GetSequenceNumber

func (n CedraNode) GetSequenceNumber(address string) (uint64, error)

GetSequenceNumber retrieves the current sequence number for the specified account address. Returns the sequence number as a uint64, or an error if the request fails.

func (CedraNode) SubmitTransaction

func (n CedraNode) SubmitTransaction(tx []byte) (string, error)

SubmitTransaction submits a signed transaction to the Cedra node. Returns the transaction hash if successful, or an error if submission fails.

func (CedraNode) WaitTxByHash

func (n CedraNode) WaitTxByHash(txHash string) (TransactionDTO, error)

WaitTxByHash waits for a transaction to be processed and returns its status from the Cedra node. This method queries the node's wait endpoint for the specified transaction hash. Returns the transaction DTO containing the transaction details and status, or an error if the request fails.

type Chain

type Chain struct {
	// CedraNodeUrl is the base URL for the Cedra node API.
	CedraNodeUrl string
	// ChainID is the identifier for this chain.
	ChainID ChainID
}

Chain represents the configuration for a Cedra blockchain network.

type ChainConfig

type ChainConfig map[ChainID]Chain

ChainConfig is a map of chain IDs to their corresponding chain configurations.

type ChainID

type ChainID uint8

ChainID represents a blockchain network identifier.

const (
	// DevnetChainID is the chain identifier for the development network.
	DevnetChainID ChainID = 3
	// TestnetChainID is the chain identifier for the test network.
	TestnetChainID ChainID = 2
	// MainnetChainID is the chain identifier for the main network.
	MainnetChainID ChainID = 1
)

func NewLocalnetChainID

func NewLocalnetChainID(id uint8) ChainID

NewLocalnetChainID creates a new chain ID for a local network. Panics if the provided ID is 0, as chain IDs must be greater than 0.

type EstimateGasPriceDTO

type EstimateGasPriceDTO struct {
	// DeprioritizedGasEstimate is the gas price estimate for deprioritized transactions.
	DeprioritizedGasEstimate uint64 `json:"deprioritized_gas_estimate"`
	// GasEstimate is the standard gas price estimate.
	GasEstimate uint64 `json:"gas_estimate"`
	// PrioritizedGasEstimate is the gas price estimate for prioritized transactions.
	PrioritizedGasEstimate uint64 `json:"prioritized_gas_estimate"`
}

EstimateGasPriceDTO represents the gas price estimates returned from the Cedra node API.

type FaAddress

type FaAddress struct {
	// Address is the 32-byte creator / metadata owner address.
	Address [32]byte
	// Symbol is the asset symbol bytes (e.g. "USDCT", "Cedra").
	Symbol []byte
}

FaAddress is the fee-asset identity used by the publisher/API: creator address + symbol. On the signed RawTransaction this is stored as a Move TypeTag (legacy BCS).

func NativeCedraFaAddress

func NativeCedraFaAddress() FaAddress

NativeCedraFaAddress returns the fee identity for native Cedra coin (0x1, "Cedra").

func NewFaAddress

func NewFaAddress(tag string) (FaAddress, error)

NewFaAddress parses a fee-asset identity. Accepted formats:

  • "address::symbol"
  • "address::module::symbol" (module is ignored)

func NewFaAddressFromParts

func NewFaAddressFromParts(address, symbol string) (FaAddress, error)

NewFaAddressFromParts builds a fee identity from a hex address and symbol string.

func (FaAddress) ToBCSBytes

func (fa FaAddress) ToBCSBytes() []byte

ToBCSBytes encodes the fee identity as a TypeTag on RawTransaction. Native Cedra is 0x1::cedra_coin::CedraCoin. FA coins are address::::. Empty is TypeTag::Bool.

func (FaAddress) UseFeeV2

func (fa FaAddress) UseFeeV2() bool

type GasUnitPrice

type GasUnitPrice uint64

func (GasUnitPrice) ToBCSBytes

func (s GasUnitPrice) ToBCSBytes() []byte

func (GasUnitPrice) ToUint64

func (s GasUnitPrice) ToUint64() uint64

type MaxGasAmount

type MaxGasAmount uint64

func (MaxGasAmount) ToBCSBytes

func (s MaxGasAmount) ToBCSBytes() []byte

func (MaxGasAmount) ToUint64

func (s MaxGasAmount) ToUint64() uint64

type SenderAuth

type SenderAuth struct {
	// PKey is the public key of the transaction sender.
	PKey []byte
	// Signature is the ED25519 signature of the transaction.
	Signature []byte
}

SenderAuth contains the authentication data for a transaction sender.

func NewSenderAuth

func NewSenderAuth(pKey []byte, signature []byte) SenderAuth

NewSenderAuth creates a new SenderAuth instance with the provided public key and signature.

func (SenderAuth) EncodeBSC

func (a SenderAuth) EncodeBSC() []byte

EncodeBSC encodes the sender authentication into Binary Canonical Serialization (BCS) format. Returns the serialized byte representation of the authentication data.

type SequenceNumber

type SequenceNumber uint64

func (SequenceNumber) ToBCSBytes

func (s SequenceNumber) ToBCSBytes() []byte

func (SequenceNumber) ToUint64

func (s SequenceNumber) ToUint64() uint64

type StructTag

type StructTag struct {
	// Address is the 32-byte address of the module.
	Address [32]byte
	// Module is the name of the module.
	Module string
	// Name is the name of the type.
	Name string
}

StructTag represents a type identifier in the Cedra blockchain. It consists of an address, module name, and type name.

func NewStringStructTag

func NewStringStructTag(tag string) (StructTag, error)

NewStringStructTag parses a struct tag string in the format "address::module::name" and creates a StructTag instance. The address can optionally include the "0x" prefix. Returns an error if the tag format is invalid.

func (*StructTag) ToBCSBytes

func (st *StructTag) ToBCSBytes() []byte

ToBCSBytes encodes the struct tag into Binary Canonical Serialization (BCS) format. Returns the serialized byte representation of the struct tag.

type Transaction

type Transaction struct {
	// Sender is the account that will sign and submit the transaction.
	Sender Account
	// Payload contains the transaction payload (module, function, arguments).
	Payload TransactionPayload
	// FaAddress is the fee-asset identity (creator address + symbol).
	// Empty (zero value), native Cedra (0x1, "Cedra"), or an FA coin are all valid.
	// Empty must not be rewritten to native Cedra, or the signature will not verify.
	FaAddress FaAddress
	// SequenceNumber is the sequence number for the sender account.
	SequenceNumber SequenceNumber
	// MaxGasAmount is the maximum amount of gas units the transaction can consume.
	MaxGasAmount MaxGasAmount
	// GasUnitPrice is the price per gas unit.
	GasUnitPrice GasUnitPrice
	// ExpirationTimestampSeconds is the Unix timestamp when the transaction expires.
	ExpirationTimestampSeconds uint64
	// ChainId identifies the blockchain network.
	ChainId uint8
}

Transaction represents a complete Cedra blockchain transaction. Fields are grouped by size for optimal memory alignment.

func (*Transaction) SetFeeCoin

func (tx *Transaction) SetFeeCoin(coin string) error

SetFeeCoin sets the fee-asset identity for the transaction. Accepts "address::symbol" or "address::module::symbol" (module is ignored).

func (*Transaction) Sign

func (tx *Transaction) Sign() ([]byte, CedraAuthenticator)

Sign signs the transaction using the sender's private key and creates an authenticator. Returns the encoded transaction bytes and the authenticator for submission. The transaction is signed with the ED25519 private key after hashing with the transaction prefix.

func (*Transaction) ToBCSBytes

func (tx *Transaction) ToBCSBytes() []byte

ToBCSBytes encodes the transaction into Binary Canonical Serialization (BCS) format. Returns the serialized byte representation of the transaction.

type TransactionDTO

type TransactionDTO struct {
	// Hash is the transaction hash returned after submission.
	Hash string `json:"hash"`
	// VMStatus is the virtual machine execution status of the transaction (e.g., "Executed successfully").
	VMStatus string `json:"vm_status"`
	// TxType is the type of the transaction (e.g., "pending_transaction" for pending transactions).
	TxType string `json:"type"`
}

TransactionDTO represents the transaction response from the Cedra node API.

type TransactionPayload

type TransactionPayload struct {
	// ModuleAddress is the 32-byte address of the module to call.
	ModuleAddress [32]byte
	// ModuleName is the name of the module containing the function.
	ModuleName string
	// FunctionName is the name of the function to call.
	FunctionName string
	// Arguments is a slice of byte arrays representing the function arguments.
	Arguments [][]byte
}

TransactionPayload represents the payload of a Cedra transaction. It specifies which module function to call and with what arguments.

func (*TransactionPayload) ToBCSBytes

func (p *TransactionPayload) ToBCSBytes() []byte

ToBCSBytes encodes the transaction payload into Binary Canonical Serialization (BCS) format. Returns the serialized byte representation of the payload.

Directories

Path Synopsis
examples
deploy_package command
transfer command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL