aptos

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2024 License: Apache-2.0 Imports: 25 Imported by: 4

README

Go Reference Go Report Card GitHub go.mod Go version GitHub Tag

aptos-go-sdk

An SDK for the Aptos blockchain in Go. The SDK is currently in Beta.

Getting started

Add go to your go.mod file

go get -u  github.com/aptos-labs/aptos-go-sdk

Where can I see examples?

Take a look at examples/ for some examples of how to write clients.

Where can I learn more?

You can read more about the Go SDK documentation on aptos.dev

Feature support

  • BCS encoding and decoding
  • Structured API parsing
  • Ed25519 Signer support
  • Secp256k1 Signer support
  • On-chain and off-chain multi-sig support
  • Sponsored transaction and Multi-agent support
  • Fungible Asset support
  • Indexer support with limited queries
  • Transaction submission and waiting
  • External signer support e.g. HSMs or external services
  • Move Package publishing support
  • Move script support
  • Transaction Simulation
TODO
  • MultiEd25519 support
  • Predetermined Indexer queries for Fungible Assets and Digital Assets
  • Automated sequence number management for parallel transaction submission

Examples

  • Transaction signing
  • Fungible asset usage
  • External and alternative signing methods
  • On-chain multi-sig
  • Performance differences between transaction submission methods
  • Move package publishing support
TODO
  • Multi-agent example
  • Script Example
  • Sponsored transaction example
  • Off-chain multi-sig example
  • Digital assets / NFTs example
  • Transaction parsing example (by blocks)

Other TODO

  • Ensure blocks fetch all transactions associated
  • More testing around API parsing
  • TypeTag string parsing
  • Add examples into the documentation

Documentation

Overview

Package aptos is a Go interface into the Aptos blockchain.

You can create a client and send a transfer transaction with the below example:

// Create a Client
client := NewClient(DevnetConfig)

// Create an account, and fund it
account := NewEd25519Account()
err := client.Fund(account.AccountAddress())
if err != nil {
  panic(fmt.Sprintf("Failed to fund account %s %w", account.AccountAddress().ToString(), err))
}

// Send funds to a different address
receiver := &AccountAddress{}
receiver.ParseStringRelaxed("0xcafe")

// Build a transaction to send 1 APT to the receiver
amount := 100_000_000 // 1 APT
transferTransaction, err := APTTransferTransaction(client, account, receiver, amount)
if err != nil {
  panic(fmt.Sprintf("Failed to build transaction %w", err))
}

// Submit transaction to the blockchain
submitResponse, err := client.SubmitTransaction(transferTransaction)
if err != nil {
  panic(fmt.Sprintf("Failed to submit transaction %w", err))
}

// Wait for transaction to complete
err := client.WaitForTransaction(submitResponse.Hash)
if err != nil {
  panic(fmt.Sprintf("Failed to wait for transaction %w", err))
}

Index

Constants

View Source
const (
	DefaultMaxGasAmount      = uint64(100_000) // Default to 0.001 APT max gas amount
	DefaultGasUnitPrice      = uint64(100)     // Default to min gas price
	DefaultExpirationSeconds = int64(300)      // Default to 5 minutes
)
View Source
const ClientHeader = "x-aptos-client"
View Source
const ContentTypeAptosSignedTxnBcs = "application/x.aptos.signed_transaction+bcs"

ContentTypeAptosSignedTxnBcs header for sending BCS transaction payloads

View Source
const ContentTypeAptosViewFunctionBcs = "application/x.aptos.view_function+bcs"

ContentTypeAptosViewFunctionBcs header for sending BCS view function payloads

View Source
const HttpErrSummaryLength = 1000

Variables

View Source
var AccountFour = types.AccountFour

AccountFour represents the 0x4 address

View Source
var AccountOne = types.AccountOne

AccountOne represents the 0x1 address

View Source
var AccountThree = types.AccountThree

AccountThree represents the 0x3 address

View Source
var AccountTwo = types.AccountTwo

AccountTwo represents the 0x2 address

View Source
var AccountZero = types.AccountZero

AccountZero represents the 0x0 address

View Source
var AptosCoinTypeTag = TypeTag{&StructTag{
	Address: AccountOne,
	Module:  "aptos_coin",
	Name:    "AptosCoin",
}}

AptosCoinTypeTag is the TypeTag for 0x1::aptos_coin::AptosCoin

View Source
var ClientHeaderValue = "aptos-go-sdk/unk"
View Source
var DevnetConfig = NetworkConfig{
	Name:       "devnet",
	NodeUrl:    "https://api.devnet.aptoslabs.com/v1",
	IndexerUrl: "https://api.devnet.aptoslabs.com/v1/graphql",
	FaucetUrl:  "https://faucet.devnet.aptoslabs.com/",
}

DevnetConfig is for use with devnet. Note devnet resets at least weekly. ChainId differs after each reset.

View Source
var LocalnetConfig = NetworkConfig{
	Name:    "localnet",
	ChainId: 4,

	NodeUrl:    "http://127.0.0.1:8080/v1",
	IndexerUrl: "http://127.0.0.1:8090/v1/graphql",
	FaucetUrl:  "http://127.0.0.1:8081",
}

LocalnetConfig is for use with a localnet, created by the [Aptos CLI](https://aptos.dev/tools/aptos-cli)

To start a localnet, install the Aptos CLI then run:

aptos node run-localnet --with-indexer-api
View Source
var MainnetConfig = NetworkConfig{
	Name:       "mainnet",
	ChainId:    1,
	NodeUrl:    "https://api.mainnet.aptoslabs.com/v1",
	IndexerUrl: "https://api.mainnet.aptoslabs.com/v1/graphql",
	FaucetUrl:  "",
}

MainnetConfig is for use with mainnet. There is no faucet for Mainnet, as these are real user assets.

View Source
var NamedNetworks map[string]NetworkConfig

NamedNetworks Map from network name to NetworkConfig

View Source
var TestnetConfig = NetworkConfig{
	Name:       "testnet",
	ChainId:    2,
	NodeUrl:    "https://api.testnet.aptoslabs.com/v1",
	IndexerUrl: "https://api.testnet.aptoslabs.com/v1/graphql",
	FaucetUrl:  "https://faucet.testnet.aptoslabs.com/",
}

TestnetConfig is for use with testnet. Testnet does not reset.

View Source
var TransactionPrefix *[]byte

TransactionPrefix is a cached hash prefix for taking transaction hashes

Functions

func BytesToHex added in v0.3.0

func BytesToHex(bytes []byte) string

BytesToHex converts bytes to a 0x prefixed hex string

func Get added in v0.4.0

func Get[T any](rc *NodeClient, getUrl string) (out T, err error)

func ParseHex

func ParseHex(hexStr string) ([]byte, error)

ParseHex Convenience function to deal with 0x at the beginning of hex strings

func Post added in v0.4.0

func Post[T any](rc *NodeClient, postUrl string, contentType string, body io.Reader) (data T, err error)

func RawTransactionPrehash

func RawTransactionPrehash() []byte

RawTransactionPrehash Return the sha3-256 prehash for RawTransaction Do not write to the []byte returned

func RawTransactionWithDataPrehash added in v0.2.0

func RawTransactionWithDataPrehash() []byte

RawTransactionWithDataPrehash Return the sha3-256 prehash for RawTransactionWithData Do not write to the []byte returned

func Sha3256Hash added in v0.2.0

func Sha3256Hash(bytes [][]byte) (output []byte)

Sha3256Hash takes a hash of the given sets of bytes

func StrToBigInt added in v0.3.0

func StrToBigInt(val string) (num *big.Int, err error)

StrToBigInt converts a string to a big.Int

func StrToUint64 added in v0.3.0

func StrToUint64(s string) (uint64, error)

StrToUint64 converts a string to a uint64

Types

type Account

type Account = types.Account

Account is a wrapper for a signer, handling the AccountAddress and signing

func NewAccountFromSigner added in v0.2.0

func NewAccountFromSigner(signer crypto.Signer, authKey ...crypto.AuthenticationKey) (*Account, error)

NewAccountFromSigner creates an account from a Signer, which is most commonly a private key

func NewEd25519Account

func NewEd25519Account() (*Account, error)

NewEd25519Account creates a legacy Ed25519 account, this is most commonly used in wallets

func NewEd25519SingleSenderAccount added in v0.2.0

func NewEd25519SingleSenderAccount() (*Account, error)

NewEd25519SingleSenderAccount creates a single signer Ed25519 account

func NewSecp256k1Account added in v0.2.0

func NewSecp256k1Account() (*Account, error)

NewSecp256k1Account creates a Secp256k1 account

type AccountAddress

type AccountAddress = types.AccountAddress

AccountAddress is a 32 byte address on the Aptos blockchain It can represent an Object, an Account, and much more.

type AccountInfo

type AccountInfo struct {
	SequenceNumberStr    string `json:"sequence_number"`
	AuthenticationKeyHex string `json:"authentication_key"`
}

AccountInfo is returned from calls to #Account()

func (AccountInfo) AuthenticationKey

func (ai AccountInfo) AuthenticationKey() ([]byte, error)

AuthenticationKey Hex decode of AuthenticationKeyHex

func (AccountInfo) SequenceNumber

func (ai AccountInfo) SequenceNumber() (uint64, error)

SequenceNumber ParseUint of SequenceNumberStr

type AccountResourceInfo

type AccountResourceInfo struct {
	// e.g. "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>"
	Type string `json:"type"`

	// Decoded from Move contract data, could really be anything
	Data map[string]any `json:"data"`
}

AccountResourceInfo is returned by #AccountResource() and #AccountResources()

type AccountResourceRecord

type AccountResourceRecord struct {
	// Account::Module::Name
	Tag StructTag

	// BCS data as stored by Move contract
	Data []byte
}

AccountResourceRecord DeserializeSequence[AccountResourceRecord](bcs) approximates the Rust side BTreeMap<StructTag,Vec<u8>> They should BCS the same with a prefix Uleb128 length followed by (StructTag,[]byte) pairs.

func (*AccountResourceRecord) MarshalBCS

func (aar *AccountResourceRecord) MarshalBCS(ser *bcs.Serializer)

func (*AccountResourceRecord) UnmarshalBCS

func (aar *AccountResourceRecord) UnmarshalBCS(des *bcs.Deserializer)

type AdditionalSigners added in v0.2.0

type AdditionalSigners []AccountAddress

type AddressTag added in v0.2.0

type AddressTag struct{}

func (*AddressTag) GetType added in v0.2.0

func (xt *AddressTag) GetType() TypeTagVariant

func (*AddressTag) MarshalBCS added in v0.2.0

func (xt *AddressTag) MarshalBCS(_ *bcs.Serializer)

func (*AddressTag) String added in v0.2.0

func (xt *AddressTag) String() string

func (*AddressTag) UnmarshalBCS added in v0.2.0

func (xt *AddressTag) UnmarshalBCS(_ *bcs.Deserializer)

type BoolTag

type BoolTag struct{}

func (*BoolTag) GetType

func (xt *BoolTag) GetType() TypeTagVariant

func (*BoolTag) MarshalBCS

func (xt *BoolTag) MarshalBCS(_ *bcs.Serializer)

func (*BoolTag) String

func (xt *BoolTag) String() string

func (*BoolTag) UnmarshalBCS

func (xt *BoolTag) UnmarshalBCS(_ *bcs.Deserializer)

type ChainIdOption

type ChainIdOption uint8

type Client

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

Client is a facade over the multiple types of underlying clients, as the user doesn't actually care where the data comes from. It will be then handled underneath

To create a new client, please use NewClient. An example below for Devnet:

client := NewClient(DevnetConfig)

func NewClient

func NewClient(config NetworkConfig) (client *Client, err error)

NewClient Creates a new client with a specific network config that can be extended in the future

func (*Client) Account

func (client *Client) Account(address AccountAddress, ledgerVersion ...uint64) (info AccountInfo, err error)

Account Retrieves information about the account such as SequenceNumber and crypto.AuthenticationKey

func (*Client) AccountAPTBalance added in v0.2.0

func (client *Client) AccountAPTBalance(address AccountAddress) (uint64, error)

AccountAPTBalance retrieves the APT balance in the account

func (*Client) AccountResource

func (client *Client) AccountResource(address AccountAddress, resourceType string, ledgerVersion ...uint64) (data map[string]any, err error)

AccountResource Retrieves a single resource given its struct name.

address := AccountOne
dataMap, _ := client.AccountResource(address, "0x1::coin::CoinStore")

Can also fetch at a specific ledger version

address := AccountOne
dataMap, _ := client.AccountResource(address, "0x1::coin::CoinStore", 1)

func (*Client) AccountResources

func (client *Client) AccountResources(address AccountAddress, ledgerVersion ...uint64) (resources []AccountResourceInfo, err error)

AccountResources fetches resources for an account into a JSON-like map[string]any in AccountResourceInfo.Data For fetching raw Move structs as BCS, See #AccountResourcesBCS

address := AccountOne
dataMap, _ := client.AccountResources(address)

Can also fetch at a specific ledger version

address := AccountOne
dataMap, _ := client.AccountResource(address, 1)

func (*Client) AccountResourcesBCS

func (client *Client) AccountResourcesBCS(address AccountAddress, ledgerVersion ...uint64) (resources []AccountResourceRecord, err error)

AccountResourcesBCS fetches account resources as raw Move struct BCS blobs in AccountResourceRecord.Data []byte

func (*Client) BlockByHeight added in v0.2.0

func (client *Client) BlockByHeight(blockHeight uint64, withTransactions bool) (data *api.Block, err error)

BlockByHeight fetches a block by height

block, _ := client.BlockByHeight(1, false)

Can also fetch with transactions

block, _ := client.BlockByHeight(1, true)

func (*Client) BlockByVersion added in v0.2.0

func (client *Client) BlockByVersion(ledgerVersion uint64, withTransactions bool) (data *api.Block, err error)

BlockByVersion fetches a block by ledger version

block, _ := client.BlockByVersion(123, false)

Can also fetch with transactions

block, _ := client.BlockByVersion(123, true)

func (*Client) BuildSignAndSubmitTransaction

func (client *Client) BuildSignAndSubmitTransaction(sender *Account, payload TransactionPayload, options ...any) (data *api.SubmitTransactionResponse, err error)

BuildSignAndSubmitTransaction Convenience function to do all three in one for more configuration, please use them separately

sender := NewEd25519Account()
txnPayload := TransactionPayload{
	Payload: &EntryFunction{
		Module: ModuleId{
			Address: AccountOne,
			Name: "aptos_account",
		},
		Function: "transfer",
		ArgTypes: []TypeTag{},
		Args: [][]byte{
			dest[:],
			amountBytes,
		},
	}
}
submitResponse, err := client.BuildSignAndSubmitTransaction(sender, txnPayload)

func (*Client) BuildTransaction

func (client *Client) BuildTransaction(sender AccountAddress, payload TransactionPayload, options ...any) (rawTxn *RawTransaction, err error)

BuildTransaction Builds a raw transaction from the payload and fetches any necessary information from on-chain

sender := NewEd25519Account()
txnPayload := TransactionPayload{
	Payload: &EntryFunction{
		Module: ModuleId{
			Address: AccountOne,
			Name: "aptos_account",
		},
		Function: "transfer",
		ArgTypes: []TypeTag{},
		Args: [][]byte{
			dest[:],
			amountBytes,
		},
	}
}
rawTxn, err := client.BuildTransaction(sender.AccountAddress(), txnPayload)

func (*Client) BuildTransactionMultiAgent added in v0.5.0

func (client *Client) BuildTransactionMultiAgent(sender AccountAddress, payload TransactionPayload, options ...any) (rawTxn *RawTransactionWithData, err error)

BuildTransactionMultiAgent Builds a raw transaction for MultiAgent or FeePayer from the payload and fetches any necessary information from on-chain

sender := NewEd25519Account()
txnPayload := TransactionPayload{
	Payload: &EntryFunction{
		Module: ModuleId{
			Address: AccountOne,
			Name: "aptos_account",
		},
		Function: "transfer",
		ArgTypes: []TypeTag{},
		Args: [][]byte{
			dest[:],
			amountBytes,
		},
	}
}
rawTxn, err := client.BuildTransactionMultiAgent(sender.AccountAddress(), txnPayload, FeePayer(AccountZero))

func (*Client) EstimateGasPrice added in v0.2.0

func (client *Client) EstimateGasPrice() (info EstimateGasInfo, err error)

EstimateGasPrice Retrieves the gas estimate from the network.

func (*Client) FetchNextMultisigAddress added in v0.2.0

func (client *Client) FetchNextMultisigAddress(address AccountAddress) (*AccountAddress, error)

FetchNextMultisigAddress retrieves the next multisig address to be created from the given account

func (*Client) Fund

func (client *Client) Fund(address AccountAddress, amount uint64) error

Fund Uses the faucet to fund an address, only applies to non-production networks

func (*Client) GetChainId

func (client *Client) GetChainId() (chainId uint8, err error)

GetChainId Retrieves the ChainId of the network Note this will be cached forever, or taken directly from the config

func (*Client) GetCoinBalances added in v0.2.0

func (client *Client) GetCoinBalances(address AccountAddress) ([]CoinBalance, error)

GetCoinBalances gets the balances of all coins associated with a given address

func (*Client) GetProcessorStatus added in v0.2.0

func (client *Client) GetProcessorStatus(processorName string) (uint64, error)

GetProcessorStatus returns the ledger version up to which the processor has processed

func (*Client) Info

func (client *Client) Info() (info NodeInfo, err error)

Info Retrieves the node info about the network and it's current state

func (*Client) NodeAPIHealthCheck added in v0.5.0

func (client *Client) NodeAPIHealthCheck(durationSecs ...uint64) (api.HealthCheckResponse, error)

NodeAPIHealthCheck checks if the node is within durationSecs of the current time, if not provided the node default is used

func (*Client) PollForTransactions

func (client *Client) PollForTransactions(txnHashes []string, options ...any) error

PollForTransactions Waits up to 10 seconds for transactions to be done, polling at 10Hz Accepts options PollPeriod and PollTimeout which should wrap time.Duration values.

hashes := []string{"0x1234", "0x4567"}
err := client.PollForTransactions(hashes)

Can additionally configure different options

hashes := []string{"0x1234", "0x4567"}
err := client.PollForTransactions(hashes, PollPeriod(500 * time.Milliseconds), PollTimeout(5 * time.Seconds))

func (*Client) QueryIndexer added in v0.2.0

func (client *Client) QueryIndexer(query any, variables map[string]any, options ...graphql.Option) error

QueryIndexer queries the indexer using GraphQL to fill the `query` struct with data. See examples in the indexer client on how to make queries

var out []CoinBalance
var q struct {
	Current_coin_balances []struct {
		CoinType     string `graphql:"coin_type"`
		Amount       uint64
		OwnerAddress string `graphql:"owner_address"`
	} `graphql:"current_coin_balances(where: {owner_address: {_eq: $address}})"`
}
variables := map[string]any{
	"address": address.StringLong(),
}
err := client.QueryIndexer(&q, variables)
if err != nil {
	return nil, err
}

for _, coin := range q.Current_coin_balances {
	out = append(out, CoinBalance{
		CoinType: coin.CoinType,
		Amount:   coin.Amount,
})
}

return out, nil

func (*Client) SetTimeout

func (client *Client) SetTimeout(timeout time.Duration)

SetTimeout adjusts the HTTP client timeout

client.SetTimeout(5 * time.Millisecond)

func (*Client) SimulateTransaction added in v0.4.0

func (client *Client) SimulateTransaction(rawTxn *RawTransaction, sender TransactionSigner, options ...any) (data []*api.UserTransaction, err error)

SimulateTransaction Simulates a raw transaction without sending it to the blockchain

func (*Client) SubmitTransaction

func (client *Client) SubmitTransaction(signedTransaction *SignedTransaction) (data *api.SubmitTransactionResponse, err error)

SubmitTransaction Submits an already signed transaction to the blockchain

func (*Client) TransactionByHash

func (client *Client) TransactionByHash(txnHash string) (data *api.Transaction, err error)

TransactionByHash gets info on a transaction The transaction may be pending or recently committed.

data, err := client.TransactionByHash("0xabcd")
if err != nil {
	if httpErr, ok := err.(aptos.HttpError) {
		if httpErr.StatusCode == 404 {
			// if we're sure this has been submitted, assume it is still pending elsewhere in the mempool
		}
	}
} else {
	if data["type"] == "pending_transaction" {
		// known to local mempool, but not committed yet
	}
}

func (*Client) TransactionByVersion

func (client *Client) TransactionByVersion(version uint64) (data *api.Transaction, err error)

TransactionByVersion gets info on a transaction from its LedgerVersion. It must have been committed to have a ledger version

data, err := client.TransactionByVersion("0xabcd")
if err != nil {
	if httpErr, ok := err.(aptos.HttpError) {
		if httpErr.StatusCode == 404 {
			// if we're sure this has been submitted, the full node might not be caught up to this version yet
		}
	}
}

func (*Client) Transactions

func (client *Client) Transactions(start *uint64, limit *uint64) (data []*api.Transaction, err error)

Transactions Get recent transactions. Start is a version number. Nil for most recent transactions. Limit is a number of transactions to return. 'about a hundred' by default.

client.Transactions(0, 2)   // Returns 2 transactions
client.Transactions(1, 100) // Returns 100 transactions

func (*Client) View

func (client *Client) View(payload *ViewPayload, ledgerVersion ...uint64) (vals []any, err error)

View Runs a view function on chain returning a list of return values.

 address := AccountOne
	payload := &ViewPayload{
		Module: ModuleId{
			Address: AccountOne,
			Name:    "coin",
		},
		Function: "balance",
		ArgTypes: []TypeTag{AptosCoinTypeTag},
		Args:     [][]byte{address[:]},
	}
	vals, err := client.aptosClient.View(payload)
	balance := StrToU64(vals.(any[])[0].(string))

func (*Client) WaitForTransaction

func (client *Client) WaitForTransaction(txnHash string) (data *api.UserTransaction, err error)

WaitForTransaction Do a long-GET for one transaction and wait for it to complete

type CoinBalance added in v0.2.0

type CoinBalance struct {
	CoinType string
	Amount   uint64
}

type ConcResponse added in v0.3.0

type ConcResponse[T any] struct {
	Result T
	Err    error
}

ConcResponse is a concurrent response wrapper as a return type for all APIs. It is meant to specifically be used in channels.

type Ed25519TransactionAuthenticator added in v0.2.0

type Ed25519TransactionAuthenticator struct {
	Sender *crypto.AccountAuthenticator
}

Ed25519TransactionAuthenticator for legacy ED25519 accounts Implements TransactionAuthenticatorImpl, bcs.Struct

func (*Ed25519TransactionAuthenticator) MarshalBCS added in v0.2.0

func (ea *Ed25519TransactionAuthenticator) MarshalBCS(ser *bcs.Serializer)

func (*Ed25519TransactionAuthenticator) UnmarshalBCS added in v0.2.0

func (ea *Ed25519TransactionAuthenticator) UnmarshalBCS(des *bcs.Deserializer)

func (*Ed25519TransactionAuthenticator) Verify added in v0.2.0

func (ea *Ed25519TransactionAuthenticator) Verify(msg []byte) bool

type EntryFunction

type EntryFunction struct {
	Module   ModuleId
	Function string
	ArgTypes []TypeTag
	Args     [][]byte
}

EntryFunction call a single published entry function arguments are ordered BCS encoded bytes

func CoinBatchTransferPayload added in v0.3.0

func CoinBatchTransferPayload(coinType *TypeTag, dests []AccountAddress, amounts []uint64) (payload *EntryFunction, err error)

CoinBatchTransferPayload builds an EntryFunction payload for transferring coins to multiple receivers

For coinType, if none is provided, it will transfer 0x1::aptos_coin:AptosCoin

func CoinTransferPayload added in v0.2.0

func CoinTransferPayload(coinType *TypeTag, dest AccountAddress, amount uint64) (payload *EntryFunction, err error)

CoinTransferPayload builds an EntryFunction payload for transferring coins

For coinType, if none is provided, it will transfer 0x1::aptos_coin:AptosCoin

func FungibleAssetPrimaryStoreTransferPayload added in v0.2.0

func FungibleAssetPrimaryStoreTransferPayload(faMetadataAddress *AccountAddress, dest AccountAddress, amount uint64) (payload *EntryFunction, err error)

FungibleAssetPrimaryStoreTransferPayload builds an EntryFunction payload to transfer between two primary stores This is similar to CoinTransferPayload

For now, if metadata is nil, then it will fail to build, but in the future, APT will be the default

func FungibleAssetTransferPayload added in v0.2.0

func FungibleAssetTransferPayload(faMetadataAddress *AccountAddress, source AccountAddress, dest AccountAddress, amount uint64) (payload *EntryFunction, err error)

FungibleAssetTransferPayload builds an EntryFunction payload to transfer between two fungible asset stores

For now, if metadata is nil, then it will fail to build, but in the future, APT will be the default

func MultisigAddOwnerPayload added in v0.2.0

func MultisigAddOwnerPayload(owner AccountAddress) *EntryFunction

MultisigAddOwnerPayload creates a payload to add an owner from the multisig

func MultisigApprovePayload added in v0.2.0

func MultisigApprovePayload(multisigAddress AccountAddress, transactionId uint64) (*EntryFunction, error)

MultisigApprovePayload generates a payload for approving a transaction on-chain. The caller must be an owner of the multisig

func MultisigChangeThresholdPayload added in v0.2.0

func MultisigChangeThresholdPayload(numSignaturesRequired uint64) (*EntryFunction, error)

MultisigChangeThresholdPayload creates a payload to change the number of signatures required for a transaction to pass.

For example, changing a 2-of-3 to a 3-of-3, the value for numSignaturesRequired would be 3

func MultisigCreateAccountPayload added in v0.2.0

func MultisigCreateAccountPayload(requiredSigners uint64, additionalAddresses []AccountAddress, metadataKeys []string, metadataValues []byte) (*EntryFunction, error)

MultisigCreateAccountPayload creates a payload for setting up a multisig

Required signers must be between 1 and the number of addresses total (sender + additional addresses). Metadata values must be BCS encoded values

func MultisigCreateTransactionPayload added in v0.2.0

func MultisigCreateTransactionPayload(multisigAddress AccountAddress, payload *MultisigTransactionPayload) (*EntryFunction, error)

MultisigCreateTransactionPayload creates a transaction to be voted upon in an on-chain multisig

Note, this serializes an EntryFunction payload, and sends it as an argument in the transaction. If the entry function payload is large, use MultisigCreateTransactionPayloadWithHash. The advantage of this over the hash version, is visibility on-chain.

func MultisigCreateTransactionPayloadWithHash added in v0.2.0

func MultisigCreateTransactionPayloadWithHash(multisigAddress AccountAddress, payload *MultisigTransactionPayload) (*EntryFunction, error)

MultisigCreateTransactionPayloadWithHash creates a transaction to be voted upon in an on-chain multisig

This differs from MultisigCreateTransactionPayload by instead taking a SHA3-256 hash of the payload and using that as the identifier of the transaction. The transaction intent will not be stored on-chain, only the hash of it.

func MultisigRejectPayload added in v0.2.0

func MultisigRejectPayload(multisigAddress AccountAddress, transactionId uint64) (*EntryFunction, error)

MultisigRejectPayload generates a payload for rejecting a transaction on-chain. The caller must be an owner of the multisig

func MultisigRemoveOwnerPayload added in v0.2.0

func MultisigRemoveOwnerPayload(owner AccountAddress) *EntryFunction

MultisigRemoveOwnerPayload creates a payload to remove an owner from the multisig

func (*EntryFunction) MarshalBCS

func (sf *EntryFunction) MarshalBCS(ser *bcs.Serializer)

func (*EntryFunction) PayloadType added in v0.2.0

func (sf *EntryFunction) PayloadType() TransactionPayloadVariant

func (*EntryFunction) UnmarshalBCS

func (sf *EntryFunction) UnmarshalBCS(des *bcs.Deserializer)

type EstimateGasInfo added in v0.2.0

type EstimateGasInfo struct {
	DeprioritizedGasEstimate uint64 `json:"deprioritized_gas_estimate"`
	GasEstimate              uint64 `json:"gas_estimate"`
	PrioritizedGasEstimate   uint64 `json:"prioritized_gas_estimate"`
}

EstimateGasInfo is returned by #EstimateGasPrice()

type EstimateGasUnitPrice added in v0.4.0

type EstimateGasUnitPrice bool

type EstimateMaxGasAmount added in v0.4.0

type EstimateMaxGasAmount bool

type EstimatePrioritizedGasUnitPrice added in v0.4.0

type EstimatePrioritizedGasUnitPrice bool

type ExpirationSeconds

type ExpirationSeconds int64

type FaucetClient

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

FaucetClient uses the underlying NodeClient to request for APT for gas on a network. This can only be used in a test network (e.g. Localnet, Devnet, Testnet)

func NewFaucetClient added in v0.2.0

func NewFaucetClient(nodeClient *NodeClient, faucetUrl string) (*FaucetClient, error)

NewFaucetClient creates a new client specifically for requesting faucet funds

func (*FaucetClient) Fund

func (faucetClient *FaucetClient) Fund(address AccountAddress, amount uint64) error

Fund account with the given amount of AptosCoin

type FeePayer added in v0.2.0

type FeePayer *AccountAddress

type FeePayerTransactionAuthenticator added in v0.2.0

type FeePayerTransactionAuthenticator struct {
	Sender                   *crypto.AccountAuthenticator
	SecondarySignerAddresses []AccountAddress
	SecondarySigners         []crypto.AccountAuthenticator
	FeePayer                 *AccountAddress
	FeePayerAuthenticator    *crypto.AccountAuthenticator
}

func (*FeePayerTransactionAuthenticator) MarshalBCS added in v0.2.0

func (ea *FeePayerTransactionAuthenticator) MarshalBCS(ser *bcs.Serializer)

func (*FeePayerTransactionAuthenticator) UnmarshalBCS added in v0.2.0

func (ea *FeePayerTransactionAuthenticator) UnmarshalBCS(des *bcs.Deserializer)

func (*FeePayerTransactionAuthenticator) Verify added in v0.2.0

func (ea *FeePayerTransactionAuthenticator) Verify(msg []byte) bool

type FungibleAssetClient

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

FungibleAssetClient This is an example client around a single fungible asset

func NewFungibleAssetClient

func NewFungibleAssetClient(client *Client, metadataAddress *AccountAddress) (faClient *FungibleAssetClient, err error)

NewFungibleAssetClient verifies the address exists when creating the client TODO: Add lookup of other metadata information such as symbol, supply, etc

func (*FungibleAssetClient) Balance

func (client *FungibleAssetClient) Balance(storeAddress *AccountAddress) (balance uint64, err error)

func (*FungibleAssetClient) Decimals

func (client *FungibleAssetClient) Decimals() (decimals uint8, err error)

func (*FungibleAssetClient) IsFrozen

func (client *FungibleAssetClient) IsFrozen(storeAddress *AccountAddress) (isFrozen bool, err error)

func (*FungibleAssetClient) Maximum

func (client *FungibleAssetClient) Maximum() (maximum *big.Int, err error)

func (*FungibleAssetClient) Name

func (client *FungibleAssetClient) Name() (name string, err error)

func (*FungibleAssetClient) PrimaryBalance

func (client *FungibleAssetClient) PrimaryBalance(owner *AccountAddress) (balance uint64, err error)

func (*FungibleAssetClient) PrimaryIsFrozen

func (client *FungibleAssetClient) PrimaryIsFrozen(owner *AccountAddress) (isFrozen bool, err error)

func (*FungibleAssetClient) PrimaryStoreAddress

func (client *FungibleAssetClient) PrimaryStoreAddress(owner *AccountAddress) (address *AccountAddress, err error)

func (*FungibleAssetClient) PrimaryStoreExists

func (client *FungibleAssetClient) PrimaryStoreExists(owner *AccountAddress) (exists bool, err error)

func (*FungibleAssetClient) StoreExists

func (client *FungibleAssetClient) StoreExists(storeAddress *AccountAddress) (exists bool, err error)

func (*FungibleAssetClient) StoreMetadata

func (client *FungibleAssetClient) StoreMetadata(storeAddress *AccountAddress) (metadataAddress *AccountAddress, err error)

func (*FungibleAssetClient) Supply

func (client *FungibleAssetClient) Supply() (supply *big.Int, err error)

func (*FungibleAssetClient) Symbol

func (client *FungibleAssetClient) Symbol() (symbol string, err error)

func (*FungibleAssetClient) Transfer

func (client *FungibleAssetClient) Transfer(sender TransactionSigner, senderStore AccountAddress, receiverStore AccountAddress, amount uint64) (signedTxn *SignedTransaction, err error)

func (*FungibleAssetClient) TransferPrimaryStore

func (client *FungibleAssetClient) TransferPrimaryStore(sender TransactionSigner, receiverAddress AccountAddress, amount uint64) (signedTxn *SignedTransaction, err error)

type GasUnitPrice

type GasUnitPrice uint64

type HttpError

type HttpError struct {
	Status     string // e.g. "200 OK"
	StatusCode int    // e.g. 200
	Header     http.Header
	Method     string
	RequestUrl url.URL
	Body       []byte
}

func NewHttpError

func NewHttpError(response *http.Response) *HttpError

func (*HttpError) Error

func (he *HttpError) Error() string

implement error interface

type IndexerClient added in v0.2.0

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

IndexerClient is a GraphQL client specifically for requesting for data from the Aptos indexer

func NewIndexerClient added in v0.2.0

func NewIndexerClient(httpClient *http.Client, url string) *IndexerClient

func (*IndexerClient) GetCoinBalances added in v0.2.0

func (ic *IndexerClient) GetCoinBalances(address AccountAddress) ([]CoinBalance, error)

GetCoinBalances retrieve the coin balances for all coins owned by the address

func (*IndexerClient) GetProcessorStatus added in v0.2.0

func (ic *IndexerClient) GetProcessorStatus(processorName string) (uint64, error)

GetProcessorStatus tells the most updated version of the transaction processor. This helps to determine freshness of data.

func (*IndexerClient) Query added in v0.2.0

func (ic *IndexerClient) Query(query any, variables map[string]any, options ...graphql.Option) error

Query is a generic function for making any GraphQL query against the indexer

func (*IndexerClient) WaitOnIndexer added in v0.2.0

func (ic *IndexerClient) WaitOnIndexer(processorName string, requestedVersion uint64) error

WaitOnIndexer waits for the indexer processorName specified to catch up to the requestedVersion

type MaxGasAmount

type MaxGasAmount uint64

type ModuleBundle

type ModuleBundle struct{}

ModuleBundle is long deprecated and no longer used, but exist as an enum position in TransactionPayload

func (*ModuleBundle) MarshalBCS

func (txn *ModuleBundle) MarshalBCS(ser *bcs.Serializer)

func (*ModuleBundle) PayloadType added in v0.2.0

func (txn *ModuleBundle) PayloadType() TransactionPayloadVariant

func (*ModuleBundle) UnmarshalBCS

func (txn *ModuleBundle) UnmarshalBCS(des *bcs.Deserializer)

type ModuleId

type ModuleId struct {
	Address AccountAddress
	Name    string
}

ModuleId the identifier for a module e.g. 0x1::coin

func (*ModuleId) MarshalBCS

func (mod *ModuleId) MarshalBCS(ser *bcs.Serializer)

func (*ModuleId) UnmarshalBCS

func (mod *ModuleId) UnmarshalBCS(des *bcs.Deserializer)

type MultiAgentRawTransactionWithData added in v0.2.0

type MultiAgentRawTransactionWithData struct {
	RawTxn           *RawTransaction
	SecondarySigners []AccountAddress
}

func (*MultiAgentRawTransactionWithData) MarshalBCS added in v0.2.0

func (txn *MultiAgentRawTransactionWithData) MarshalBCS(ser *bcs.Serializer)

func (*MultiAgentRawTransactionWithData) UnmarshalBCS added in v0.2.0

func (txn *MultiAgentRawTransactionWithData) UnmarshalBCS(des *bcs.Deserializer)

type MultiAgentTransactionAuthenticator added in v0.2.0

type MultiAgentTransactionAuthenticator struct {
	Sender                   *crypto.AccountAuthenticator
	SecondarySignerAddresses []AccountAddress
	SecondarySigners         []crypto.AccountAuthenticator
}

func (*MultiAgentTransactionAuthenticator) MarshalBCS added in v0.2.0

func (ea *MultiAgentTransactionAuthenticator) MarshalBCS(ser *bcs.Serializer)

func (*MultiAgentTransactionAuthenticator) UnmarshalBCS added in v0.2.0

func (ea *MultiAgentTransactionAuthenticator) UnmarshalBCS(des *bcs.Deserializer)

func (*MultiAgentTransactionAuthenticator) Verify added in v0.2.0

func (ea *MultiAgentTransactionAuthenticator) Verify(msg []byte) bool

type MultiAgentWithFeePayerRawTransactionWithData added in v0.2.0

type MultiAgentWithFeePayerRawTransactionWithData struct {
	RawTxn           *RawTransaction
	SecondarySigners []AccountAddress
	FeePayer         *AccountAddress
}

func (*MultiAgentWithFeePayerRawTransactionWithData) MarshalBCS added in v0.2.0

func (*MultiAgentWithFeePayerRawTransactionWithData) UnmarshalBCS added in v0.2.0

type MultiEd25519TransactionAuthenticator added in v0.2.0

type MultiEd25519TransactionAuthenticator struct {
	Sender *crypto.AccountAuthenticator
}

func (*MultiEd25519TransactionAuthenticator) MarshalBCS added in v0.2.0

func (*MultiEd25519TransactionAuthenticator) UnmarshalBCS added in v0.2.0

func (ea *MultiEd25519TransactionAuthenticator) UnmarshalBCS(des *bcs.Deserializer)

func (*MultiEd25519TransactionAuthenticator) Verify added in v0.2.0

type Multisig added in v0.2.0

type Multisig struct {
	MultisigAddress AccountAddress
	Payload         *MultisigTransactionPayload // Optional
}

Multisig is an on-chain multisig transaction, that calls an entry function associated

func (*Multisig) MarshalBCS added in v0.2.0

func (sf *Multisig) MarshalBCS(ser *bcs.Serializer)

func (*Multisig) PayloadType added in v0.2.0

func (sf *Multisig) PayloadType() TransactionPayloadVariant

func (*Multisig) UnmarshalBCS added in v0.2.0

func (sf *Multisig) UnmarshalBCS(des *bcs.Deserializer)

type MultisigTransactionImpl added in v0.2.0

type MultisigTransactionImpl interface {
	bcs.Struct
}

type MultisigTransactionPayload added in v0.2.0

type MultisigTransactionPayload struct {
	Variant MultisigTransactionPayloadVariant
	Payload MultisigTransactionImpl
}

MultisigTransactionPayload is an enum allowing for multiple types of transactions to be called via multisig

Note this does not implement TransactionPayloadImpl

func (*MultisigTransactionPayload) MarshalBCS added in v0.2.0

func (sf *MultisigTransactionPayload) MarshalBCS(ser *bcs.Serializer)

func (*MultisigTransactionPayload) UnmarshalBCS added in v0.2.0

func (sf *MultisigTransactionPayload) UnmarshalBCS(des *bcs.Deserializer)

type MultisigTransactionPayloadVariant added in v0.2.0

type MultisigTransactionPayloadVariant uint32
const (
	MultisigTransactionPayloadVariantEntryFunction MultisigTransactionPayloadVariant = 0
)

type NetworkConfig

type NetworkConfig struct {
	Name       string
	ChainId    uint8
	NodeUrl    string
	IndexerUrl string
	FaucetUrl  string
}

NetworkConfig a configuration for the Client and which network to use. Use one of the preconfigured LocalnetConfig, DevnetConfig, TestnetConfig, or MainnetConfig unless you have your own full node.

Name, ChainId, IndexerUrl, FaucetUrl are not required.

If ChainId is 0, the ChainId wil be fetched on-chain If IndexerUrl or FaucetUrl are an empty string "", clients will not be made for them.

type NodeClient

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

func NewNodeClient added in v0.2.0

func NewNodeClient(rpcUrl string, chainId uint8) (*NodeClient, error)

func NewNodeClientWithHttpClient added in v0.2.0

func NewNodeClientWithHttpClient(rpcUrl string, chainId uint8, client *http.Client) (*NodeClient, error)

func (*NodeClient) Account

func (rc *NodeClient) Account(address AccountAddress, ledgerVersion ...uint64) (info AccountInfo, err error)

func (*NodeClient) AccountAPTBalance added in v0.2.0

func (rc *NodeClient) AccountAPTBalance(account AccountAddress) (balance uint64, err error)

func (*NodeClient) AccountResource

func (rc *NodeClient) AccountResource(address AccountAddress, resourceType string, ledgerVersion ...uint64) (data map[string]any, err error)

func (*NodeClient) AccountResources

func (rc *NodeClient) AccountResources(address AccountAddress, ledgerVersion ...uint64) (resources []AccountResourceInfo, err error)

AccountResources fetches resources for an account into a JSON-like map[string]any in AccountResourceInfo.Data For fetching raw Move structs as BCS, See #AccountResourcesBCS

func (*NodeClient) AccountResourcesBCS

func (rc *NodeClient) AccountResourcesBCS(address AccountAddress, ledgerVersion ...uint64) (resources []AccountResourceRecord, err error)

AccountResourcesBCS fetches account resources as raw Move struct BCS blobs in AccountResourceRecord.Data []byte

func (*NodeClient) BlockByHeight added in v0.2.0

func (rc *NodeClient) BlockByHeight(blockHeight uint64, withTransactions bool) (data *api.Block, err error)

func (*NodeClient) BlockByVersion added in v0.2.0

func (rc *NodeClient) BlockByVersion(ledgerVersion uint64, withTransactions bool) (data *api.Block, err error)

func (*NodeClient) BuildSignAndSubmitTransaction

func (rc *NodeClient) BuildSignAndSubmitTransaction(sender TransactionSigner, payload TransactionPayload, options ...any) (data *api.SubmitTransactionResponse, err error)

func (*NodeClient) BuildSignAndSubmitTransactions added in v0.4.0

func (rc *NodeClient) BuildSignAndSubmitTransactions(
	sender TransactionSigner,
	payloads chan TransactionSubmissionPayload,
	responses chan TransactionSubmissionResponse,
)

BuildSignAndSubmitTransactions starts up a goroutine to process transactions for a single [TransactionSender]

func (*NodeClient) BuildSignAndSubmitTransactionsWithSignFunction added in v0.4.0

func (rc *NodeClient) BuildSignAndSubmitTransactionsWithSignFunction(
	sender AccountAddress,
	payloads chan TransactionSubmissionPayload,
	responses chan TransactionSubmissionResponse,
	sign func(rawTxn RawTransactionImpl) (*SignedTransaction, error),
)

BuildSignAndSubmitTransactionsWithSignFunction allows for signing with a custom function

This enables the ability to do fee payer, and other approaches while staying concurrent

func Example() {
	client := NewNodeClient()

	sender := NewEd25519Account()
	feePayer := NewEd25519Account()

	payloads := make(chan TransactionSubmissionPayload)
	responses := make(chan TransactionSubmissionResponse)

	signingFunc := func(rawTxn RawTransactionImpl) (*SignedTransaction, error) {
		switch rawTxn.(type) {
		case *RawTransaction:
			return nil, fmt.Errorf("only fee payer supported")
		case *RawTransactionWithData:
			rawTxnWithData := rawTxn.(*RawTransactionWithData)
			switch rawTxnWithData.Variant {
			case MultiAgentRawTransactionWithDataVariant:
				return nil, fmt.Errorf("multi agent not supported, please provide a fee payer function")
			case MultiAgentWithFeePayerRawTransactionWithDataVariant:
				rawTxnWithData.Sign(sender)
				txn, ok := rawTxnWithData.ToFeePayerTransaction()
			default:
				return nil, fmt.Errorf("unsupported rawTransactionWithData type")
			}
		default:
			return nil, fmt.Errorf("unsupported rawTransactionImpl type")
		}
	}

	// startup worker
	go client.BuildSignAndSubmitTransactionsWithSignFunction(
		sender,
		payloads,
		responses,
		signingFunc
	)

	// Here add payloads, and wiating on resposnes

}

func (*NodeClient) BuildTransaction

func (rc *NodeClient) BuildTransaction(sender AccountAddress, payload TransactionPayload, options ...any) (rawTxn *RawTransaction, err error)

BuildTransaction builds a raw transaction for signing Accepts options: MaxGasAmount, GasUnitPrice, ExpirationSeconds, SequenceNumber, ChainIdOption, FeePayer, AdditionalSigners

func (*NodeClient) BuildTransactionMultiAgent added in v0.2.0

func (rc *NodeClient) BuildTransactionMultiAgent(sender AccountAddress, payload TransactionPayload, options ...any) (rawTxnImpl *RawTransactionWithData, err error)

BuildTransactionMultiAgent builds a raw transaction for signing with fee payer or multi-agent Accepts options: MaxGasAmount, GasUnitPrice, ExpirationSeconds, SequenceNumber, ChainIdOption, FeePayer, AdditionalSigners

func (*NodeClient) BuildTransactions added in v0.4.0

func (rc *NodeClient) BuildTransactions(sender AccountAddress, payloads chan TransactionSubmissionPayload, responses chan TransactionBuildResponse, setSequenceNumber chan uint64)

BuildTransactions start a goroutine to process TransactionPayload and spit out RawTransactionImpl.

TODO: add optional arguments for configuring transactions as a whole?

func (*NodeClient) EstimateGasPrice added in v0.2.0

func (rc *NodeClient) EstimateGasPrice() (info EstimateGasInfo, err error)

TODO: add caching for some period of time

func (*NodeClient) GetBCS

func (rc *NodeClient) GetBCS(getUrl string) (out []byte, err error)

func (*NodeClient) GetChainId

func (rc *NodeClient) GetChainId() (chainId uint8, err error)

func (*NodeClient) Info

func (rc *NodeClient) Info() (info NodeInfo, err error)

func (*NodeClient) NodeHealthCheck added in v0.5.0

func (rc *NodeClient) NodeHealthCheck(durationSecs ...uint64) (api.HealthCheckResponse, error)

func (*NodeClient) PollForTransaction added in v0.2.0

func (rc *NodeClient) PollForTransaction(hash string, options ...any) (*api.UserTransaction, error)

func (*NodeClient) PollForTransactions

func (rc *NodeClient) PollForTransactions(txnHashes []string, options ...any) error

PollForTransactions waits up to 10 seconds for transactions to be done, polling at 10Hz Accepts options PollPeriod and PollTimeout which should wrap time.Duration values.

func (*NodeClient) SimulateTransaction added in v0.4.0

func (rc *NodeClient) SimulateTransaction(rawTxn *RawTransaction, sender TransactionSigner, options ...any) (data []*api.UserTransaction, err error)

func (*NodeClient) SubmitTransaction

func (rc *NodeClient) SubmitTransaction(signedTxn *SignedTransaction) (data *api.SubmitTransactionResponse, err error)

func (*NodeClient) SubmitTransactions added in v0.4.0

func (rc *NodeClient) SubmitTransactions(signedTxns chan *SignedTransaction, responses chan TransactionSubmissionResponse)

SubmitTransactions starts up a worker for sending signed transactions to on-chain

func (*NodeClient) TransactionByHash

func (rc *NodeClient) TransactionByHash(txnHash string) (data *api.Transaction, err error)

TransactionByHash gets info on a transaction The transaction may be pending or recently committed.

data, err := c.TransactionByHash("0xabcd")
if err != nil {
	if httpErr, ok := err.(aptos.HttpError) {
		if httpErr.StatusCode == 404 {
			// if we're sure this has been submitted, assume it is still pending elsewhere in the mempool
		}
	}
} else {
	if data["type"] == "pending_transaction" {
		// known to local mempool, but not committed yet
	}
}

func (*NodeClient) TransactionByVersion

func (rc *NodeClient) TransactionByVersion(version uint64) (data *api.Transaction, err error)

func (*NodeClient) Transactions

func (rc *NodeClient) Transactions(start *uint64, limit *uint64) (data []*api.Transaction, err error)

Transactions Get recent transactions. Start is a version number. Nil for most recent transactions. Limit is a number of transactions to return. 'about a hundred' by default.

func (*NodeClient) View

func (rc *NodeClient) View(payload *ViewPayload, ledgerVersion ...uint64) (data []any, err error)

func (*NodeClient) WaitForTransaction

func (rc *NodeClient) WaitForTransaction(txnHash string, options ...any) (data *api.UserTransaction, err error)

WaitForTransaction does a long-GET for one transaction and wait for it to complete. Initially poll at 10 Hz for up to 1 second if node replies with 404 (wait for txn to propagate). Accept option arguments PollPeriod and PollTimeout like PollForTransactions.

type NodeInfo

type NodeInfo struct {
	ChainId                uint8  `json:"chain_id"`
	EpochStr               string `json:"epoch"`
	LedgerTimestampStr     string `json:"ledger_timestamp"`
	LedgerVersionStr       string `json:"ledger_version"`
	OldestLedgerVersionStr string `json:"oldest_ledger_version"`
	NodeRole               string `json:"node_role"`
	BlockHeightStr         string `json:"block_height"`
	OldestBlockHeightStr   string `json:"oldest_block_height"`
	GitHash                string `json:"git_hash"`
}

NodeInfo information retrieved about the current state of the blockchain on API requests

func (NodeInfo) BlockHeight

func (info NodeInfo) BlockHeight() uint64

BlockHeight the newest block available on the full node (by the time you call this there's already a new one!)

func (NodeInfo) Epoch

func (info NodeInfo) Epoch() uint64

Epoch the current epoch of the network. On Mainnet, this is usually every 2 hours.

func (NodeInfo) LedgerTimestamp added in v0.2.0

func (info NodeInfo) LedgerTimestamp() uint64

LedgerTimestamp is the timestamp the block was committed

func (NodeInfo) LedgerVersion

func (info NodeInfo) LedgerVersion() uint64

LedgerVersion the newest transaction available on the full node

func (NodeInfo) OldestBlockHeight

func (info NodeInfo) OldestBlockHeight() uint64

OldestBlockHeight the oldest block note pruned on the full node

func (NodeInfo) OldestLedgerVersion

func (info NodeInfo) OldestLedgerVersion() uint64

OldestLedgerVersion the oldest ledger version not pruned on the full node

type PollPeriod

type PollPeriod time.Duration

PollPeriod is an option to PollForTransactions

type PollTimeout

type PollTimeout time.Duration

PollTimeout is an option to PollForTransactions

type RawTransaction

type RawTransaction struct {
	Sender         AccountAddress
	SequenceNumber uint64
	Payload        TransactionPayload
	MaxGasAmount   uint64
	GasUnitPrice   uint64

	// ExpirationTimestampSeconds is seconds since Unix epoch
	ExpirationTimestampSeconds uint64

	ChainId uint8
}

RawTransaction representation of a transaction's parts prior to signing Implements crypto.MessageSigner, crypto.Signer, bcs.Struct

func APTTransferTransaction

func APTTransferTransaction(client *Client, sender TransactionSigner, dest AccountAddress, amount uint64, options ...any) (rawTxn *RawTransaction, err error)

APTTransferTransaction Move some APT from sender to dest, only for single signer Amount in Octas (10^-8 APT)

options may be: MaxGasAmount, GasUnitPrice, ExpirationSeconds, ValidUntil, SequenceNumber, ChainIdOption deprecated, please use the EntryFunction APIs

func (*RawTransaction) MarshalBCS

func (txn *RawTransaction) MarshalBCS(ser *bcs.Serializer)

func (*RawTransaction) Sign

func (txn *RawTransaction) Sign(signer crypto.Signer) (authenticator *crypto.AccountAuthenticator, err error)

func (*RawTransaction) SignedTransaction added in v0.2.0

func (txn *RawTransaction) SignedTransaction(sender crypto.Signer) (*SignedTransaction, error)

func (*RawTransaction) SignedTransactionWithAuthenticator added in v0.2.0

func (txn *RawTransaction) SignedTransactionWithAuthenticator(auth *crypto.AccountAuthenticator) (*SignedTransaction, error)

SignedTransactionWithAuthenticator signs the sender only signed transaction

func (*RawTransaction) SigningMessage added in v0.2.0

func (txn *RawTransaction) SigningMessage() (message []byte, err error)

SigningMessage generates the bytes needed to be signed by a signer

func (*RawTransaction) UnmarshalBCS

func (txn *RawTransaction) UnmarshalBCS(des *bcs.Deserializer)

type RawTransactionImpl added in v0.2.0

type RawTransactionImpl interface {
	bcs.Struct

	// SigningMessage creates a raw signing message for the transaction
	// Note that this should only be used externally if signing transactions outside the SDK.  Otherwise, use Sign.
	SigningMessage() (message []byte, err error)

	// Sign signs a transaction and returns the associated AccountAuthenticator, it will underneath sign the SigningMessage
	Sign(signer crypto.Signer) (*crypto.AccountAuthenticator, error)
}

type RawTransactionWithData added in v0.2.0

type RawTransactionWithData struct {
	Variant RawTransactionWithDataVariant
	Inner   RawTransactionWithDataImpl
}

func (*RawTransactionWithData) MarshalBCS added in v0.2.0

func (txn *RawTransactionWithData) MarshalBCS(ser *bcs.Serializer)

func (*RawTransactionWithData) SetFeePayer added in v0.5.0

func (txn *RawTransactionWithData) SetFeePayer(
	feePayer AccountAddress,
) bool

func (*RawTransactionWithData) Sign added in v0.2.0

func (txn *RawTransactionWithData) Sign(signer crypto.Signer) (authenticator *crypto.AccountAuthenticator, err error)

func (*RawTransactionWithData) SigningMessage added in v0.2.0

func (txn *RawTransactionWithData) SigningMessage() (message []byte, err error)

func (*RawTransactionWithData) ToFeePayerSignedTransaction added in v0.2.0

func (txn *RawTransactionWithData) ToFeePayerSignedTransaction(
	sender *crypto.AccountAuthenticator,
	feePayerAuthenticator *crypto.AccountAuthenticator,
	additionalSigners []crypto.AccountAuthenticator,
) (*SignedTransaction, bool)

func (*RawTransactionWithData) ToMultiAgentSignedTransaction added in v0.2.0

func (txn *RawTransactionWithData) ToMultiAgentSignedTransaction(
	sender *crypto.AccountAuthenticator,
	additionalSigners []crypto.AccountAuthenticator,
) (*SignedTransaction, bool)

func (*RawTransactionWithData) UnmarshalBCS added in v0.2.0

func (txn *RawTransactionWithData) UnmarshalBCS(des *bcs.Deserializer)

type RawTransactionWithDataImpl added in v0.2.0

type RawTransactionWithDataImpl interface {
	bcs.Struct
}

type RawTransactionWithDataVariant added in v0.2.0

type RawTransactionWithDataVariant uint32
const (
	MultiAgentRawTransactionWithDataVariant             RawTransactionWithDataVariant = 0
	MultiAgentWithFeePayerRawTransactionWithDataVariant RawTransactionWithDataVariant = 1
)

type Script

type Script struct {
	Code     []byte
	ArgTypes []TypeTag
	Args     []ScriptArgument
}

Script A Move script as compiled code as a transaction

func (*Script) MarshalBCS

func (s *Script) MarshalBCS(ser *bcs.Serializer)

func (*Script) PayloadType added in v0.2.0

func (s *Script) PayloadType() TransactionPayloadVariant

func (*Script) UnmarshalBCS

func (s *Script) UnmarshalBCS(des *bcs.Deserializer)

type ScriptArgument

type ScriptArgument struct {
	Variant ScriptArgumentVariant
	Value   any // TODO: Do we add better typing, or stick with the any
}

ScriptArgument a Move script argument, which encodes its type with it

func (*ScriptArgument) MarshalBCS

func (sa *ScriptArgument) MarshalBCS(ser *bcs.Serializer)

func (*ScriptArgument) UnmarshalBCS

func (sa *ScriptArgument) UnmarshalBCS(des *bcs.Deserializer)

type ScriptArgumentVariant

type ScriptArgumentVariant uint32
const (
	ScriptArgumentU8       ScriptArgumentVariant = 0
	ScriptArgumentU64      ScriptArgumentVariant = 1
	ScriptArgumentU128     ScriptArgumentVariant = 2
	ScriptArgumentAddress  ScriptArgumentVariant = 3
	ScriptArgumentU8Vector ScriptArgumentVariant = 4
	ScriptArgumentBool     ScriptArgumentVariant = 5
	ScriptArgumentU16      ScriptArgumentVariant = 6
	ScriptArgumentU32      ScriptArgumentVariant = 7
	ScriptArgumentU256     ScriptArgumentVariant = 8
)

type SequenceNumber

type SequenceNumber uint64

type SequenceNumberTracker added in v0.4.0

type SequenceNumberTracker struct {
	SequenceNumber uint64
	Mutex          sync.Mutex
}

func (*SequenceNumberTracker) Increment added in v0.4.0

func (snt *SequenceNumberTracker) Increment() uint64

func (*SequenceNumberTracker) Update added in v0.4.0

func (snt *SequenceNumberTracker) Update(new uint64) uint64

type SignedTransaction

type SignedTransaction struct {
	Transaction   RawTransactionImpl
	Authenticator *TransactionAuthenticator
}

SignedTransaction a raw transaction plus its authenticator for a fully verifiable message

func (*SignedTransaction) Hash added in v0.2.0

func (txn *SignedTransaction) Hash() (string, error)

Hash takes the hash of the SignedTransaction

Note: At the moment, this assumes that the transaction is a UserTransaction

func (*SignedTransaction) MarshalBCS

func (txn *SignedTransaction) MarshalBCS(ser *bcs.Serializer)

func (*SignedTransaction) UnmarshalBCS

func (txn *SignedTransaction) UnmarshalBCS(des *bcs.Deserializer)

func (*SignedTransaction) Verify

func (txn *SignedTransaction) Verify() error

Verify checks a signed transaction's signature

type SignedTransactionVariant added in v0.2.0

type SignedTransactionVariant uint8
const UserTransactionVariant SignedTransactionVariant = 0

type SignerTag added in v0.2.0

type SignerTag struct{}

func (*SignerTag) GetType added in v0.2.0

func (xt *SignerTag) GetType() TypeTagVariant

func (*SignerTag) MarshalBCS added in v0.2.0

func (xt *SignerTag) MarshalBCS(_ *bcs.Serializer)

func (*SignerTag) String added in v0.2.0

func (xt *SignerTag) String() string

func (*SignerTag) UnmarshalBCS added in v0.2.0

func (xt *SignerTag) UnmarshalBCS(_ *bcs.Deserializer)

type SingleSenderTransactionAuthenticator added in v0.2.0

type SingleSenderTransactionAuthenticator struct {
	Sender *crypto.AccountAuthenticator
}

func (*SingleSenderTransactionAuthenticator) MarshalBCS added in v0.2.0

func (*SingleSenderTransactionAuthenticator) UnmarshalBCS added in v0.2.0

func (ea *SingleSenderTransactionAuthenticator) UnmarshalBCS(des *bcs.Deserializer)

func (*SingleSenderTransactionAuthenticator) Verify added in v0.2.0

type StructTag

type StructTag struct {
	Address    AccountAddress
	Module     string
	Name       string
	TypeParams []TypeTag
}

StructTag represents an on-chain struct of the form address::module::name<T1,T2,...>

func NewObjectTag added in v0.2.0

func NewObjectTag(inner TypeTagImpl) *StructTag

NewObjectTag creates a 0x1::object::Object TypeTag based on an inner type

func NewOptionTag added in v0.2.0

func NewOptionTag(inner TypeTagImpl) *StructTag

NewOptionTag creates a 0x1::option::Option TypeTag based on an inner type

func NewStringTag added in v0.2.0

func NewStringTag() *StructTag

NewStringTag creates a TypeTag for 0x1::string::String

func (*StructTag) GetType

func (xt *StructTag) GetType() TypeTagVariant

func (*StructTag) MarshalBCS

func (xt *StructTag) MarshalBCS(ser *bcs.Serializer)

func (*StructTag) String

func (xt *StructTag) String() string

String outputs to the form address::module::name<type1, type2> e.g. 0x1::string::String or 0x42::my_mod::MultiType<u8,0x1::string::String>

func (*StructTag) UnmarshalBCS

func (xt *StructTag) UnmarshalBCS(des *bcs.Deserializer)

type TransactionAuthenticator added in v0.2.0

type TransactionAuthenticator struct {
	Variant TransactionAuthenticatorVariant
	Auth    TransactionAuthenticatorImpl
}

TransactionAuthenticator is used for authorizing a transaction. This differs from crypto.AccountAuthenticator because it handles constructs like FeePayer and MultiAgent. Some keys can't stand on their own as TransactionAuthenticators. Implements TransactionAuthenticatorImpl, bcs.Struct

func NewTransactionAuthenticator added in v0.4.0

func NewTransactionAuthenticator(auth *crypto.AccountAuthenticator) (*TransactionAuthenticator, error)

func (*TransactionAuthenticator) MarshalBCS added in v0.2.0

func (ea *TransactionAuthenticator) MarshalBCS(ser *bcs.Serializer)

func (*TransactionAuthenticator) UnmarshalBCS added in v0.2.0

func (ea *TransactionAuthenticator) UnmarshalBCS(des *bcs.Deserializer)

func (*TransactionAuthenticator) Verify added in v0.2.0

func (ea *TransactionAuthenticator) Verify(msg []byte) bool

type TransactionAuthenticatorImpl added in v0.2.0

type TransactionAuthenticatorImpl interface {
	bcs.Struct
	// Verify Return true if this AccountAuthenticator approves
	Verify(data []byte) bool
}

type TransactionAuthenticatorVariant added in v0.2.0

type TransactionAuthenticatorVariant uint8
const (
	TransactionAuthenticatorEd25519      TransactionAuthenticatorVariant = 0
	TransactionAuthenticatorMultiEd25519 TransactionAuthenticatorVariant = 1
	TransactionAuthenticatorMultiAgent   TransactionAuthenticatorVariant = 2
	TransactionAuthenticatorFeePayer     TransactionAuthenticatorVariant = 3
	TransactionAuthenticatorSingleSender TransactionAuthenticatorVariant = 4
)

type TransactionBuildResponse added in v0.4.0

type TransactionBuildResponse struct {
	Id       uint64
	Response RawTransactionImpl
	Err      error
}

type TransactionPayload

type TransactionPayload struct {
	Payload TransactionPayloadImpl
}

TransactionPayload the actual instructions of which functions to call on chain

func PublishPackagePayloadFromJsonFile added in v0.2.0

func PublishPackagePayloadFromJsonFile(metadata []byte, bytecode [][]byte) (*TransactionPayload, error)

PublishPackagePayloadFromJsonFile publishes code created with the Aptos CLI to publish with it. The Aptos CLI can generate the associated file with the following CLI command:

aptos move build-publish-payload

func (*TransactionPayload) MarshalBCS

func (txn *TransactionPayload) MarshalBCS(ser *bcs.Serializer)

func (*TransactionPayload) UnmarshalBCS

func (txn *TransactionPayload) UnmarshalBCS(des *bcs.Deserializer)

type TransactionPayloadImpl added in v0.2.0

type TransactionPayloadImpl interface {
	bcs.Struct
	PayloadType() TransactionPayloadVariant // This is specifically to ensure that wrong types don't end up here
}

type TransactionPayloadVariant added in v0.2.0

type TransactionPayloadVariant uint32
const (
	TransactionPayloadVariantScript        TransactionPayloadVariant = 0
	TransactionPayloadVariantModuleBundle  TransactionPayloadVariant = 1 // Deprecated
	TransactionPayloadVariantEntryFunction TransactionPayloadVariant = 2
	TransactionPayloadVariantMultisig      TransactionPayloadVariant = 3
)

type TransactionSigner added in v0.2.0

type TransactionSigner interface {
	crypto.Signer

	// AccountAddress returns the address of the signer, this may differ from the AuthKey derived from the inner signer
	AccountAddress() AccountAddress
}

TransactionSigner is a generic interface for a way to sign transactions. The default implementation is Account

Note that AccountAddress is needed to be the correct on-chain value for proper signing. This may differ from the AuthKey provided by the crypto.Signer

type TransactionSubmissionPayload added in v0.4.0

type TransactionSubmissionPayload struct {
	Id      uint64
	Type    TransactionSubmissionType
	Inner   TransactionPayload // The actual transaction payload
	Options []any              // This is a placeholder to allow future optional arguments
}

type TransactionSubmissionResponse added in v0.4.0

type TransactionSubmissionResponse struct {
	Id       uint64
	Response *api.SubmitTransactionResponse
	Err      error
}

type TransactionSubmissionType added in v0.4.0

type TransactionSubmissionType uint8

TransactionSubmissionType is the counter for an enum

const (
	// TransactionSubmissionTypeSingle represents a single signer transaction, no multi-agent and no-fee payer
	TransactionSubmissionTypeSingle TransactionSubmissionType = iota
	// TransactionSubmissionTypeMultiAgent represents a multi-agent or fee payer transaction
	TransactionSubmissionTypeMultiAgent TransactionSubmissionType = iota
)

type TypeTag

type TypeTag struct {
	Value TypeTagImpl
}

TypeTag is a wrapper around a TypeTagImpl e.g. BoolTag or U8Tag for the purpose of serialization and deserialization Implements bcs.Struct

func NewTypeTag

func NewTypeTag(inner TypeTagImpl) TypeTag

NewTypeTag wraps a TypeTagImpl in a TypeTag

func (*TypeTag) MarshalBCS

func (tt *TypeTag) MarshalBCS(ser *bcs.Serializer)

func (*TypeTag) String

func (tt *TypeTag) String() string

String gives the canonical TypeTag string value used in Move

func (*TypeTag) UnmarshalBCS

func (tt *TypeTag) UnmarshalBCS(des *bcs.Deserializer)

type TypeTagImpl

type TypeTagImpl interface {
	bcs.Struct
	GetType() TypeTagVariant
	String() string
}

TypeTagImpl is an interface describing all the different types of TypeTag. Unfortunately because of how serialization works, a wrapper TypeTag struct is needed to handle the differentiation between types

type TypeTagVariant added in v0.2.0

type TypeTagVariant uint32
const (
	TypeTagBool    TypeTagVariant = 0
	TypeTagU8      TypeTagVariant = 1
	TypeTagU64     TypeTagVariant = 2
	TypeTagU128    TypeTagVariant = 3
	TypeTagAddress TypeTagVariant = 4
	TypeTagSigner  TypeTagVariant = 5
	TypeTagVector  TypeTagVariant = 6
	TypeTagStruct  TypeTagVariant = 7
	TypeTagU16     TypeTagVariant = 8
	TypeTagU32     TypeTagVariant = 9
	TypeTagU256    TypeTagVariant = 10
)

type U128Tag added in v0.2.0

type U128Tag struct{}

func (*U128Tag) GetType added in v0.2.0

func (xt *U128Tag) GetType() TypeTagVariant

func (*U128Tag) MarshalBCS added in v0.2.0

func (xt *U128Tag) MarshalBCS(_ *bcs.Serializer)

func (*U128Tag) String added in v0.2.0

func (xt *U128Tag) String() string

func (*U128Tag) UnmarshalBCS added in v0.2.0

func (xt *U128Tag) UnmarshalBCS(_ *bcs.Deserializer)

type U16Tag

type U16Tag struct{}

func (*U16Tag) GetType

func (xt *U16Tag) GetType() TypeTagVariant

func (*U16Tag) MarshalBCS

func (xt *U16Tag) MarshalBCS(_ *bcs.Serializer)

func (*U16Tag) String

func (xt *U16Tag) String() string

func (*U16Tag) UnmarshalBCS

func (xt *U16Tag) UnmarshalBCS(_ *bcs.Deserializer)

type U256Tag added in v0.2.0

type U256Tag struct{}

func (*U256Tag) GetType added in v0.2.0

func (xt *U256Tag) GetType() TypeTagVariant

func (*U256Tag) MarshalBCS added in v0.2.0

func (xt *U256Tag) MarshalBCS(_ *bcs.Serializer)

func (*U256Tag) String added in v0.2.0

func (xt *U256Tag) String() string

func (*U256Tag) UnmarshalBCS added in v0.2.0

func (xt *U256Tag) UnmarshalBCS(_ *bcs.Deserializer)

type U32Tag

type U32Tag struct{}

func (*U32Tag) GetType

func (xt *U32Tag) GetType() TypeTagVariant

func (*U32Tag) MarshalBCS

func (xt *U32Tag) MarshalBCS(_ *bcs.Serializer)

func (*U32Tag) String

func (xt *U32Tag) String() string

func (*U32Tag) UnmarshalBCS

func (xt *U32Tag) UnmarshalBCS(_ *bcs.Deserializer)

type U64Tag

type U64Tag struct{}

func (*U64Tag) GetType

func (xt *U64Tag) GetType() TypeTagVariant

func (*U64Tag) MarshalBCS

func (xt *U64Tag) MarshalBCS(_ *bcs.Serializer)

func (*U64Tag) String

func (xt *U64Tag) String() string

func (*U64Tag) UnmarshalBCS

func (xt *U64Tag) UnmarshalBCS(_ *bcs.Deserializer)

type U8Tag

type U8Tag struct{}

func (*U8Tag) GetType

func (xt *U8Tag) GetType() TypeTagVariant

func (*U8Tag) MarshalBCS

func (xt *U8Tag) MarshalBCS(_ *bcs.Serializer)

func (*U8Tag) String

func (xt *U8Tag) String() string

func (*U8Tag) UnmarshalBCS

func (xt *U8Tag) UnmarshalBCS(_ *bcs.Deserializer)

type VectorTag added in v0.2.0

type VectorTag struct {
	TypeParam TypeTag
}

VectorTag represents the vector<T> type in Move, where T is another TypeTag

func NewVectorTag added in v0.2.0

func NewVectorTag(inner TypeTagImpl) *VectorTag

NewVectorTag creates a TypeTag for vector<inner>

func (*VectorTag) GetType added in v0.2.0

func (xt *VectorTag) GetType() TypeTagVariant

func (*VectorTag) MarshalBCS added in v0.2.0

func (xt *VectorTag) MarshalBCS(ser *bcs.Serializer)

func (*VectorTag) String added in v0.2.0

func (xt *VectorTag) String() string

func (*VectorTag) UnmarshalBCS added in v0.2.0

func (xt *VectorTag) UnmarshalBCS(des *bcs.Deserializer)

type ViewPayload

type ViewPayload struct {
	Module   ModuleId
	Function string
	ArgTypes []TypeTag
	Args     [][]byte
}

func (*ViewPayload) MarshalBCS

func (vp *ViewPayload) MarshalBCS(ser *bcs.Serializer)

Directories

Path Synopsis
Package api represents all types associated with the Aptos REST API.
Package api represents all types associated with the Aptos REST API.
Package bcs implements [BCS].
Package bcs implements [BCS].
Package crypto handles all cryptographic types and operations associated with Aptos.
Package crypto handles all cryptographic types and operations associated with Aptos.
examples
internal

Jump to

Keyboard shortcuts

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