From 98345316f04ab77d96e40c2ce04180f1a1123c65 Mon Sep 17 00:00:00 2001 From: andrew Date: Sat, 27 Jul 2024 13:26:17 -0700 Subject: [PATCH 1/4] remove internal folder --- account.go | 2 +- api/events_test.go | 5 +++-- api/module.go | 2 +- api/module_test.go | 2 +- api/payloads.go | 3 ++- api/signature.go | 3 ++- api/transactions.go | 5 +++-- api/transactions_test.go | 5 +++-- api/util.go | 5 +++-- api/writeSet.go | 3 ++- api/writeSet_test.go | 5 +++-- crypto/authenticationKey.go | 3 ++- crypto/authenticationKey_test.go | 5 +++-- crypto/authenticator_test.go | 5 +++-- crypto/ed25519.go | 5 +++-- crypto/ed25519_test.go | 5 +++-- crypto/multiEd25519.go | 3 ++- crypto/multiKey.go | 3 ++- crypto/secp256k1.go | 3 ++- crypto/secp256k1_test.go | 5 +++-- crypto/singleKey.go | 3 ++- spec_common_test.go | 2 +- {internal/types => types}/account.go | 0 {internal/types => types}/accountAddress.go | 3 ++- {internal/types => types}/accountAddress_test.go | 0 {internal/types => types}/account_test.go | 0 {internal/types => types}/doc.go | 0 util.go | 3 ++- {internal/util => util}/util.go | 0 29 files changed, 54 insertions(+), 34 deletions(-) rename {internal/types => types}/account.go (100%) rename {internal/types => types}/accountAddress.go (98%) rename {internal/types => types}/accountAddress_test.go (100%) rename {internal/types => types}/account_test.go (100%) rename {internal/types => types}/doc.go (100%) rename {internal/util => util}/util.go (100%) diff --git a/account.go b/account.go index cf04d32..4336996 100644 --- a/account.go +++ b/account.go @@ -2,7 +2,7 @@ package aptos import ( "github.com/aptos-labs/aptos-go-sdk/crypto" - "github.com/aptos-labs/aptos-go-sdk/internal/types" + "github.com/aptos-labs/aptos-go-sdk/types" ) // Re-export types so that way the user experience doesn't change diff --git a/api/events_test.go b/api/events_test.go index 2cac26c..5792bcc 100644 --- a/api/events_test.go +++ b/api/events_test.go @@ -2,9 +2,10 @@ package api import ( "encoding/json" - "github.com/aptos-labs/aptos-go-sdk/internal/types" - "github.com/stretchr/testify/assert" "testing" + + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/stretchr/testify/assert" ) func TestEvent_V1(t *testing.T) { diff --git a/api/module.go b/api/module.go index d8c5cfb..b0a876d 100644 --- a/api/module.go +++ b/api/module.go @@ -1,7 +1,7 @@ package api import ( - "github.com/aptos-labs/aptos-go-sdk/internal/types" + "github.com/aptos-labs/aptos-go-sdk/types" ) // MoveBytecode describes a module, or script, and it's associated ABI as a [MoveModule] diff --git a/api/module_test.go b/api/module_test.go index f53334b..1a50daa 100644 --- a/api/module_test.go +++ b/api/module_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "testing" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + "github.com/aptos-labs/aptos-go-sdk/util" "github.com/stretchr/testify/assert" ) diff --git a/api/payloads.go b/api/payloads.go index 42a3f16..d23967f 100644 --- a/api/payloads.go +++ b/api/payloads.go @@ -2,7 +2,8 @@ package api import ( "encoding/json" - "github.com/aptos-labs/aptos-go-sdk/internal/types" + + "github.com/aptos-labs/aptos-go-sdk/types" ) // TransactionPayloadVariant is the type of payload represented in JSON diff --git a/api/signature.go b/api/signature.go index 3ab1600..5a0c135 100644 --- a/api/signature.go +++ b/api/signature.go @@ -2,8 +2,9 @@ package api import ( "encoding/json" + "github.com/aptos-labs/aptos-go-sdk/crypto" - "github.com/aptos-labs/aptos-go-sdk/internal/types" + "github.com/aptos-labs/aptos-go-sdk/types" ) // SignatureVariant is the JSON representation of the signature types diff --git a/api/transactions.go b/api/transactions.go index 103cca6..a9e7a8f 100644 --- a/api/transactions.go +++ b/api/transactions.go @@ -3,8 +3,9 @@ package api import ( "encoding/json" "fmt" - "github.com/aptos-labs/aptos-go-sdk/internal/types" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/aptos-labs/aptos-go-sdk/util" ) // TransactionVariant is the type of transaction, all transactions submitted by this SDK are [TransactionVariantUser] diff --git a/api/transactions_test.go b/api/transactions_test.go index 0380616..53fd273 100644 --- a/api/transactions_test.go +++ b/api/transactions_test.go @@ -2,9 +2,10 @@ package api import ( "encoding/json" - "github.com/aptos-labs/aptos-go-sdk/internal/types" - "github.com/stretchr/testify/assert" "testing" + + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/stretchr/testify/assert" ) func TestTransaction_GenesisTransaction(t *testing.T) { diff --git a/api/util.go b/api/util.go index 0090542..ecca9f9 100644 --- a/api/util.go +++ b/api/util.go @@ -2,8 +2,9 @@ package api import ( "encoding/json" - "github.com/aptos-labs/aptos-go-sdk/internal/types" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/aptos-labs/aptos-go-sdk/util" ) // GUID describes a GUID associated with things like V1 events diff --git a/api/writeSet.go b/api/writeSet.go index 9acb776..1d700e1 100644 --- a/api/writeSet.go +++ b/api/writeSet.go @@ -2,7 +2,8 @@ package api import ( "encoding/json" - "github.com/aptos-labs/aptos-go-sdk/internal/types" + + "github.com/aptos-labs/aptos-go-sdk/types" ) // WriteSetVariant is the type of [WriteSet] diff --git a/api/writeSet_test.go b/api/writeSet_test.go index 5cf8a2a..fd5ab23 100644 --- a/api/writeSet_test.go +++ b/api/writeSet_test.go @@ -2,9 +2,10 @@ package api import ( "encoding/json" - "github.com/aptos-labs/aptos-go-sdk/internal/types" - "github.com/stretchr/testify/assert" "testing" + + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/stretchr/testify/assert" ) func TestWriteSet_WriteModule(t *testing.T) { diff --git a/crypto/authenticationKey.go b/crypto/authenticationKey.go index e438928..ecd99bd 100644 --- a/crypto/authenticationKey.go +++ b/crypto/authenticationKey.go @@ -2,8 +2,9 @@ package crypto import ( "fmt" + "github.com/aptos-labs/aptos-go-sdk/bcs" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + "github.com/aptos-labs/aptos-go-sdk/util" ) //region AuthenticationKey diff --git a/crypto/authenticationKey_test.go b/crypto/authenticationKey_test.go index 89afbb8..419625a 100644 --- a/crypto/authenticationKey_test.go +++ b/crypto/authenticationKey_test.go @@ -1,9 +1,10 @@ package crypto import ( - "github.com/aptos-labs/aptos-go-sdk/internal/util" - "github.com/stretchr/testify/assert" "testing" + + "github.com/aptos-labs/aptos-go-sdk/util" + "github.com/stretchr/testify/assert" ) const testAuthKey = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" diff --git a/crypto/authenticator_test.go b/crypto/authenticator_test.go index 7f6b107..6d0667e 100644 --- a/crypto/authenticator_test.go +++ b/crypto/authenticator_test.go @@ -2,10 +2,11 @@ package crypto import ( "crypto/ed25519" + "testing" + "github.com/aptos-labs/aptos-go-sdk/bcs" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + "github.com/aptos-labs/aptos-go-sdk/util" "github.com/stretchr/testify/assert" - "testing" ) func TestAuthenticationKey_FromPublicKey(t *testing.T) { diff --git a/crypto/ed25519.go b/crypto/ed25519.go index d61222f..49ef021 100644 --- a/crypto/ed25519.go +++ b/crypto/ed25519.go @@ -4,9 +4,10 @@ import ( "crypto/ed25519" "errors" "fmt" - "github.com/aptos-labs/aptos-go-sdk/bcs" - "github.com/aptos-labs/aptos-go-sdk/internal/util" "io" + + "github.com/aptos-labs/aptos-go-sdk/bcs" + "github.com/aptos-labs/aptos-go-sdk/util" ) //region Ed25519PrivateKey diff --git a/crypto/ed25519_test.go b/crypto/ed25519_test.go index 5bb7cd4..1711706 100644 --- a/crypto/ed25519_test.go +++ b/crypto/ed25519_test.go @@ -2,10 +2,11 @@ package crypto import ( "crypto/ed25519" + "testing" + "github.com/aptos-labs/aptos-go-sdk/bcs" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + "github.com/aptos-labs/aptos-go-sdk/util" "github.com/stretchr/testify/assert" - "testing" ) const testEd25519PrivateKey = "0xc5338cd251c22daa8c9c9cc94f498cc8a5c7e1d2e75287a5dda91096fe64efa5" diff --git a/crypto/multiEd25519.go b/crypto/multiEd25519.go index 5af0961..6d752e6 100644 --- a/crypto/multiEd25519.go +++ b/crypto/multiEd25519.go @@ -3,8 +3,9 @@ package crypto import ( "crypto/ed25519" "fmt" + "github.com/aptos-labs/aptos-go-sdk/bcs" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + "github.com/aptos-labs/aptos-go-sdk/util" ) //region MultiEd25519PublicKey diff --git a/crypto/multiKey.go b/crypto/multiKey.go index 5074720..d20d861 100644 --- a/crypto/multiKey.go +++ b/crypto/multiKey.go @@ -2,8 +2,9 @@ package crypto import ( "fmt" + "github.com/aptos-labs/aptos-go-sdk/bcs" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + "github.com/aptos-labs/aptos-go-sdk/util" ) //region MultiKey diff --git a/crypto/secp256k1.go b/crypto/secp256k1.go index 1dc4868..cddee8b 100644 --- a/crypto/secp256k1.go +++ b/crypto/secp256k1.go @@ -3,8 +3,9 @@ package crypto import ( "crypto/ecdsa" "fmt" + "github.com/aptos-labs/aptos-go-sdk/bcs" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + "github.com/aptos-labs/aptos-go-sdk/util" ethCrypto "github.com/ethereum/go-ethereum/crypto" ) diff --git a/crypto/secp256k1_test.go b/crypto/secp256k1_test.go index 0d8322f..cb868c9 100644 --- a/crypto/secp256k1_test.go +++ b/crypto/secp256k1_test.go @@ -1,10 +1,11 @@ package crypto import ( + "testing" + "github.com/aptos-labs/aptos-go-sdk/bcs" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + "github.com/aptos-labs/aptos-go-sdk/util" "github.com/stretchr/testify/assert" - "testing" ) const ( diff --git a/crypto/singleKey.go b/crypto/singleKey.go index bd65e51..8319ab8 100644 --- a/crypto/singleKey.go +++ b/crypto/singleKey.go @@ -2,8 +2,9 @@ package crypto import ( "fmt" + "github.com/aptos-labs/aptos-go-sdk/bcs" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + "github.com/aptos-labs/aptos-go-sdk/util" ) //region SingleSigner diff --git a/spec_common_test.go b/spec_common_test.go index 91b935d..5d2fbe9 100644 --- a/spec_common_test.go +++ b/spec_common_test.go @@ -1,6 +1,6 @@ package aptos -import "github.com/aptos-labs/aptos-go-sdk/internal/util" +import "github.com/aptos-labs/aptos-go-sdk/util" // TODO Add specific keys that must be deserialized and compared const Test64ByteHex = "0x1234123412341234123412341234123412341234123412341234123412341234" diff --git a/internal/types/account.go b/types/account.go similarity index 100% rename from internal/types/account.go rename to types/account.go diff --git a/internal/types/accountAddress.go b/types/accountAddress.go similarity index 98% rename from internal/types/accountAddress.go rename to types/accountAddress.go index e2d8706..de16673 100644 --- a/internal/types/accountAddress.go +++ b/types/accountAddress.go @@ -3,9 +3,10 @@ package types import ( "encoding/json" "fmt" + "github.com/aptos-labs/aptos-go-sdk/bcs" "github.com/aptos-labs/aptos-go-sdk/crypto" - "github.com/aptos-labs/aptos-go-sdk/internal/util" + "github.com/aptos-labs/aptos-go-sdk/util" ) // AccountAddress a 32-byte representation of an on-chain address diff --git a/internal/types/accountAddress_test.go b/types/accountAddress_test.go similarity index 100% rename from internal/types/accountAddress_test.go rename to types/accountAddress_test.go diff --git a/internal/types/account_test.go b/types/account_test.go similarity index 100% rename from internal/types/account_test.go rename to types/account_test.go diff --git a/internal/types/doc.go b/types/doc.go similarity index 100% rename from internal/types/doc.go rename to types/doc.go diff --git a/util.go b/util.go index b07dee0..bbad7ab 100644 --- a/util.go +++ b/util.go @@ -1,8 +1,9 @@ package aptos import ( - "github.com/aptos-labs/aptos-go-sdk/internal/util" "math/big" + + "github.com/aptos-labs/aptos-go-sdk/util" ) // -- Note these are copied from internal/util/util.go to prevent package loops, but still allow devs to use it diff --git a/internal/util/util.go b/util/util.go similarity index 100% rename from internal/util/util.go rename to util/util.go From fab32b76669b06a73bf9cc860438b3dc61b424fb Mon Sep 17 00:00:00 2001 From: andrew Date: Sat, 27 Jul 2024 19:42:40 -0700 Subject: [PATCH 2/4] hard split between types and client --- account.go | 50 ----- client.go => client/client.go | 87 ++++----- client_test.go => client/client_test.go | 96 +++++----- client_util.go => client/client_util.go | 12 +- faucet.go => client/faucet.go | 6 +- .../fungible_asset_client.go | 103 +++++----- http.go => client/http.go | 2 +- indexerClient.go => client/indexerClient.go | 8 +- client/multisig.go | 180 ++++++++++++++++++ nodeClient.go => client/nodeClient.go | 86 +++++---- .../nodeClient_test.go | 5 +- nodeInfo.go => client/nodeInfo.go | 2 +- nodeInfo_test.go => client/nodeInfo_test.go | 5 +- signer_test.go => client/signer_test.go | 11 +- .../spec_client_test.go | 5 +- .../transactionSubmission.go | 67 +++---- code_test.go | 1 - examples/alternative_signing/main.go | 22 ++- examples/alternative_signing/main_test.go | 5 +- examples/external_signing/main.go | 26 +-- examples/external_signing/main_test.go | 3 +- examples/fungible_asset/main.go | 36 ++-- examples/fungible_asset/main_test.go | 3 +- examples/onchain_multisig/main.go | 130 ++++++------- examples/onchain_multisig/main_test.go | 3 +- examples/performance_transaction/main.go | 15 +- examples/performance_transaction/main_test.go | 3 +- .../sending_concurrent_transactions/main.go | 36 ++-- .../main_test.go | 3 +- examples/sponsored_transaction/main.go | 23 ++- examples/sponsored_transaction/main_test.go | 3 +- examples/transfer_coin/main.go | 45 ++--- examples/transfer_coin/main_test.go | 5 +- spec_bcs_test.go | 14 +- types/account.go | 3 +- accountInfo.go => types/accountInfo.go | 2 +- .../accountResourceInfo.go | 2 +- .../accountResourceRecord.go | 2 +- code.go => types/code.go | 2 +- types/code_test.go | 1 + coinPayloads.go => types/coinPayloads.go | 6 +- commonPayloads.go => types/commonPayloads.go | 3 +- .../estimateGasInfo.go | 2 +- .../fungible_asset_client_test.go | 10 +- moduleId.go => types/moduleId.go | 2 +- multisig.go => types/multisig.go | 32 +--- rawTransaction.go => types/rawTransaction.go | 3 +- resource_test.go => types/resource_test.go | 7 +- script.go => types/script.go | 5 +- .../signedTransaction.go | 10 +- .../transactionAuthenticator.go | 3 +- .../transactionPayload.go | 3 +- .../transactions_test.go | 5 +- typetag.go => types/typetag.go | 5 +- typetag_test.go => types/typetag_test.go | 5 +- util.go | 35 ---- util_test.go => util/util_test.go | 13 +- 57 files changed, 687 insertions(+), 575 deletions(-) delete mode 100644 account.go rename client.go => client/client.go (82%) rename client_test.go => client/client_test.go (85%) rename client_util.go => client/client_util.go (75%) rename faucet.go => client/faucet.go (91%) rename fungible_asset_client.go => client/fungible_asset_client.go (65%) rename http.go => client/http.go (99%) rename indexerClient.go => client/indexerClient.go (95%) create mode 100644 client/multisig.go rename nodeClient.go => client/nodeClient.go (90%) rename nodeClient_test.go => client/nodeClient_test.go (97%) rename nodeInfo.go => client/nodeInfo.go (99%) rename nodeInfo_test.go => client/nodeInfo_test.go (99%) rename signer_test.go => client/signer_test.go (94%) rename spec_client_test.go => client/spec_client_test.go (99%) rename transactionSubmission.go => client/transactionSubmission.go (83%) delete mode 100644 code_test.go rename accountInfo.go => types/accountInfo.go (97%) rename accountResourceInfo.go => types/accountResourceInfo.go (95%) rename accountResourceRecord.go => types/accountResourceRecord.go (97%) rename code.go => types/code.go (98%) create mode 100644 types/code_test.go rename coinPayloads.go => types/coinPayloads.go (97%) rename commonPayloads.go => types/commonPayloads.go (99%) rename estimateGasInfo.go => types/estimateGasInfo.go (97%) rename fungible_asset_client_test.go => types/fungible_asset_client_test.go (89%) rename moduleId.go => types/moduleId.go (96%) rename multisig.go => types/multisig.go (88%) rename rawTransaction.go => types/rawTransaction.go (99%) rename resource_test.go => types/resource_test.go (99%) rename script.go => types/script.go (99%) rename signedTransaction.go => types/signedTransaction.go (90%) rename transactionAuthenticator.go => types/transactionAuthenticator.go (99%) rename transactionPayload.go => types/transactionPayload.go (99%) rename transactions_test.go => types/transactions_test.go (99%) rename typetag.go => types/typetag.go (99%) rename typetag_test.go => types/typetag_test.go (99%) delete mode 100644 util.go rename util_test.go => util/util_test.go (86%) diff --git a/account.go b/account.go deleted file mode 100644 index 4336996..0000000 --- a/account.go +++ /dev/null @@ -1,50 +0,0 @@ -package aptos - -import ( - "github.com/aptos-labs/aptos-go-sdk/crypto" - "github.com/aptos-labs/aptos-go-sdk/types" -) - -// Re-export types so that way the user experience doesn't change - -// AccountAddress is a 32 byte address on the Aptos blockchain -// It can represent an Object, an Account, and much more. -type AccountAddress = types.AccountAddress - -// Account is a wrapper for a signer, handling the AccountAddress and signing -type Account = types.Account - -// AccountZero represents the 0x0 address -var AccountZero = types.AccountZero - -// AccountOne represents the 0x1 address -var AccountOne = types.AccountOne - -// AccountTwo represents the 0x2 address -var AccountTwo = types.AccountTwo - -// AccountThree represents the 0x3 address -var AccountThree = types.AccountThree - -// AccountFour represents the 0x4 address -var AccountFour = types.AccountFour - -// NewAccountFromSigner creates an account from a Signer, which is most commonly a private key -func NewAccountFromSigner(signer crypto.Signer, authKey ...crypto.AuthenticationKey) (*Account, error) { - return types.NewAccountFromSigner(signer, authKey...) -} - -// NewEd25519Account creates a legacy Ed25519 account, this is most commonly used in wallets -func NewEd25519Account() (*Account, error) { - return types.NewEd25519Account() -} - -// NewEd25519SingleSenderAccount creates a single signer Ed25519 account -func NewEd25519SingleSenderAccount() (*Account, error) { - return types.NewEd25519SingleSignerAccount() -} - -// NewSecp256k1Account creates a Secp256k1 account -func NewSecp256k1Account() (*Account, error) { - return types.NewSecp256k1Account() -} diff --git a/client.go b/client/client.go similarity index 82% rename from client.go rename to client/client.go index 99527e0..b23df8d 100644 --- a/client.go +++ b/client/client.go @@ -1,9 +1,10 @@ -package aptos +package client import ( "time" "github.com/aptos-labs/aptos-go-sdk/api" + "github.com/aptos-labs/aptos-go-sdk/types" "github.com/hasura/go-graphql-client" ) @@ -148,39 +149,39 @@ func (client *Client) Info() (info NodeInfo, err error) { } // Account Retrieves information about the account such as [SequenceNumber] and [crypto.AuthenticationKey] -func (client *Client) Account(address AccountAddress, ledgerVersion ...uint64) (info AccountInfo, err error) { +func (client *Client) Account(address types.AccountAddress, ledgerVersion ...uint64) (info types.AccountInfo, err error) { return client.nodeClient.Account(address, ledgerVersion...) } // AccountResource Retrieves a single resource given its struct name. // -// address := AccountOne +// address := types.AccountOne // dataMap, _ := client.AccountResource(address, "0x1::coin::CoinStore") // // Can also fetch at a specific ledger version // -// address := AccountOne +// address := types.AccountOne // dataMap, _ := client.AccountResource(address, "0x1::coin::CoinStore", 1) -func (client *Client) AccountResource(address AccountAddress, resourceType string, ledgerVersion ...uint64) (data map[string]any, err error) { +func (client *Client) AccountResource(address types.AccountAddress, resourceType string, ledgerVersion ...uint64) (data map[string]any, err error) { return client.nodeClient.AccountResource(address, resourceType, ledgerVersion...) } -// AccountResources fetches resources for an account into a JSON-like map[string]any in AccountResourceInfo.Data +// AccountResources fetches resources for an account into a JSON-like map[string]any in types.AccountResourceInfo.Data // For fetching raw Move structs as BCS, See #AccountResourcesBCS // -// address := AccountOne +// address := types.AccountOne // dataMap, _ := client.AccountResources(address) // // Can also fetch at a specific ledger version // -// address := AccountOne +// address := types.AccountOne // dataMap, _ := client.AccountResource(address, 1) -func (client *Client) AccountResources(address AccountAddress, ledgerVersion ...uint64) (resources []AccountResourceInfo, err error) { +func (client *Client) AccountResources(address types.AccountAddress, ledgerVersion ...uint64) (resources []types.AccountResourceInfo, err error) { return client.nodeClient.AccountResources(address, ledgerVersion...) } -// AccountResourcesBCS fetches account resources as raw Move struct BCS blobs in AccountResourceRecord.Data []byte -func (client *Client) AccountResourcesBCS(address AccountAddress, ledgerVersion ...uint64) (resources []AccountResourceRecord, err error) { +// AccountResourcesBCS fetches account resources as raw Move struct BCS blobs in types.AccountResourceRecord.Data []byte +func (client *Client) AccountResourcesBCS(address types.AccountAddress, ledgerVersion ...uint64) (resources []types.AccountResourceRecord, err error) { return client.nodeClient.AccountResourcesBCS(address, ledgerVersion...) } @@ -270,7 +271,7 @@ func (client *Client) Transactions(start *uint64, limit *uint64) (data []*api.Co } // SubmitTransaction Submits an already signed transaction to the blockchain -func (client *Client) SubmitTransaction(signedTransaction *SignedTransaction) (data *api.SubmitTransactionResponse, err error) { +func (client *Client) SubmitTransaction(signedTransaction *types.SignedTransaction) (data *api.SubmitTransactionResponse, err error) { return client.nodeClient.SubmitTransaction(signedTransaction) } @@ -278,12 +279,12 @@ func (client *Client) SubmitTransaction(signedTransaction *SignedTransaction) (d // // It will return the responses in the same order as the input transactions that failed. If the response is empty, then // all transactions succeeded. -func (client *Client) BatchSubmitTransaction(signedTxns []*SignedTransaction) (response *api.BatchSubmitTransactionResponse, err error) { +func (client *Client) BatchSubmitTransaction(signedTxns []*types.SignedTransaction) (response *api.BatchSubmitTransactionResponse, err error) { return client.nodeClient.BatchSubmitTransaction(signedTxns) } // SimulateTransaction Simulates a raw transaction without sending it to the blockchain -func (client *Client) SimulateTransaction(rawTxn *RawTransaction, sender TransactionSigner, options ...any) (data []*api.UserTransaction, err error) { +func (client *Client) SimulateTransaction(rawTxn *types.RawTransaction, sender types.TransactionSigner, options ...any) (data []*api.UserTransaction, err error) { return client.nodeClient.SimulateTransaction(rawTxn, sender, options...) } @@ -294,21 +295,21 @@ func (client *Client) GetChainId() (chainId uint8, err error) { } // Fund Uses the faucet to fund an address, only applies to non-production networks -func (client *Client) Fund(address AccountAddress, amount uint64) error { +func (client *Client) Fund(address types.AccountAddress, amount uint64) error { return client.faucetClient.Fund(address, amount) } // 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, +// sender := types.NewEd25519Account() +// txnPayload := types.TransactionPayload{ +// Payload: &types.EntryFunction{ +// Module: types.ModuleId{ +// Address: types.AccountOne, // Name: "aptos_account", // }, // Function: "transfer", -// ArgTypes: []TypeTag{}, +// ArgTypes: []types.TypeTag{}, // Args: [][]byte{ // dest[:], // amountBytes, @@ -316,21 +317,21 @@ func (client *Client) Fund(address AccountAddress, amount uint64) error { // } // } // rawTxn, err := client.BuildTransaction(sender.AccountAddress(), txnPayload) -func (client *Client) BuildTransaction(sender AccountAddress, payload TransactionPayload, options ...any) (rawTxn *RawTransaction, err error) { +func (client *Client) BuildTransaction(sender types.AccountAddress, payload types.TransactionPayload, options ...any) (rawTxn *types.RawTransaction, err error) { return client.nodeClient.BuildTransaction(sender, payload, options...) } // 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, +// sender := types.NewEd25519Account() +// txnPayload := types.TransactionPayload{ +// Payload: &types.EntryFunction{ +// Module: types.ModuleId{ +// Address: types.AccountOne, // Name: "aptos_account", // }, // Function: "transfer", -// ArgTypes: []TypeTag{}, +// ArgTypes: []types.TypeTag{}, // Args: [][]byte{ // dest[:], // amountBytes, @@ -338,22 +339,22 @@ func (client *Client) BuildTransaction(sender AccountAddress, payload Transactio // } // } // rawTxn, err := client.BuildTransactionMultiAgent(sender.AccountAddress(), txnPayload, FeePayer(AccountZero)) -func (client *Client) BuildTransactionMultiAgent(sender AccountAddress, payload TransactionPayload, options ...any) (rawTxn *RawTransactionWithData, err error) { +func (client *Client) BuildTransactionMultiAgent(sender types.AccountAddress, payload types.TransactionPayload, options ...any) (rawTxn *types.RawTransactionWithData, err error) { return client.nodeClient.BuildTransactionMultiAgent(sender, payload, options...) } // 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, +// sender := types.NewEd25519Account() +// txnPayload := types.TransactionPayload{ +// Payload: &types.EntryFunction{ +// Module: types.ModuleId{ +// Address: types.AccountOne, // Name: "aptos_account", // }, // Function: "transfer", -// ArgTypes: []TypeTag{}, +// ArgTypes: []types.TypeTag{}, // Args: [][]byte{ // dest[:], // amountBytes, @@ -361,20 +362,20 @@ func (client *Client) BuildTransactionMultiAgent(sender AccountAddress, payload // } // } // submitResponse, err := client.BuildSignAndSubmitTransaction(sender, txnPayload) -func (client *Client) BuildSignAndSubmitTransaction(sender *Account, payload TransactionPayload, options ...any) (data *api.SubmitTransactionResponse, err error) { +func (client *Client) BuildSignAndSubmitTransaction(sender *types.Account, payload types.TransactionPayload, options ...any) (data *api.SubmitTransactionResponse, err error) { return client.nodeClient.BuildSignAndSubmitTransaction(sender, payload, options...) } // View Runs a view function on chain returning a list of return values. // -// address := AccountOne +// address := types.AccountOne // payload := &ViewPayload{ -// Module: ModuleId{ -// Address: AccountOne, +// Module: types.ModuleId{ +// Address: types.AccountOne, // Name: "coin", // }, // Function: "balance", -// ArgTypes: []TypeTag{AptosCoinTypeTag}, +// ArgTypes: []types.TypeTag{types.AptosCoinTypeTag}, // Args: [][]byte{address[:]}, // } // vals, err := client.aptosClient.View(payload) @@ -384,12 +385,12 @@ func (client *Client) View(payload *ViewPayload, ledgerVersion ...uint64) (vals } // EstimateGasPrice Retrieves the gas estimate from the network. -func (client *Client) EstimateGasPrice() (info EstimateGasInfo, err error) { +func (client *Client) EstimateGasPrice() (info types.EstimateGasInfo, err error) { return client.nodeClient.EstimateGasPrice() } // AccountAPTBalance retrieves the APT balance in the account -func (client *Client) AccountAPTBalance(address AccountAddress) (uint64, error) { +func (client *Client) AccountAPTBalance(address types.AccountAddress) (uint64, error) { return client.nodeClient.AccountAPTBalance(address) } @@ -429,7 +430,7 @@ func (client *Client) GetProcessorStatus(processorName string) (uint64, error) { } // GetCoinBalances gets the balances of all coins associated with a given address -func (client *Client) GetCoinBalances(address AccountAddress) ([]CoinBalance, error) { +func (client *Client) GetCoinBalances(address types.AccountAddress) ([]CoinBalance, error) { return client.indexerClient.GetCoinBalances(address) } diff --git a/client_test.go b/client/client_test.go similarity index 85% rename from client_test.go rename to client/client_test.go index 31e5afc..240be61 100644 --- a/client_test.go +++ b/client/client_test.go @@ -1,4 +1,4 @@ -package aptos +package client import ( "strings" @@ -7,6 +7,8 @@ import ( "time" "github.com/aptos-labs/aptos-go-sdk/api" + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/aptos-labs/aptos-go-sdk/util" "github.com/stretchr/testify/assert" ) @@ -16,14 +18,22 @@ const ( vmStatusSuccess = "Executed successfully" ) -type CreateSigner func() (TransactionSigner, error) +type CreateSigner func() (types.TransactionSigner, error) var TestSigners map[string]CreateSigner -type CreateSingleSignerPayload func(client *Client, sender TransactionSigner, options ...any) (*RawTransaction, error) +type CreateSingleSignerPayload func(client *Client, sender types.TransactionSigner, options ...any) (*types.RawTransaction, error) var TestSingleSignerPayloads map[string]CreateSingleSignerPayload +var testConfig = LocalnetConfig + +// createTestClient to use for testing for only one place to configure the network +// TODO: Allow overrides with environment variable? +func createTestClient() (*Client, error) { + return NewClient(testConfig) +} + func init() { initSigners() initSingleSignerPayloads() @@ -31,26 +41,26 @@ func init() { func initSigners() { TestSigners = make(map[string]CreateSigner) - TestSigners["Standard Ed25519"] = func() (TransactionSigner, error) { - signer, err := NewEd25519Account() - return any(signer).(TransactionSigner), err + TestSigners["Standard Ed25519"] = func() (types.TransactionSigner, error) { + signer, err := types.NewEd25519Account() + return any(signer).(types.TransactionSigner), err } - TestSigners["Single Sender Ed25519"] = func() (TransactionSigner, error) { - signer, err := NewEd25519SingleSenderAccount() - return any(signer).(TransactionSigner), err + TestSigners["Single Sender Ed25519"] = func() (types.TransactionSigner, error) { + signer, err := types.NewEd25519SingleSignerAccount() + return any(signer).(types.TransactionSigner), err } - TestSigners["Single Sender Secp256k1"] = func() (TransactionSigner, error) { - signer, err := NewSecp256k1Account() - return any(signer).(TransactionSigner), err + TestSigners["Single Sender Secp256k1"] = func() (types.TransactionSigner, error) { + signer, err := types.NewSecp256k1Account() + return any(signer).(types.TransactionSigner), err } - TestSigners["2-of-3 MultiKey"] = func() (TransactionSigner, error) { + TestSigners["2-of-3 MultiKey"] = func() (types.TransactionSigner, error) { signer, err := NewMultiKeyTestSigner(3, 2) - return any(signer).(TransactionSigner), err + return any(signer).(types.TransactionSigner), err } /* TODO: MultiEd25519 is not supported ATM - TestSigners["MultiEd25519"] = func() (TransactionSigner, error) { + TestSigners["MultiEd25519"] = func() (types.TransactionSigner, error) { signer, err := NewMultiEd25519Signer(3, 2) - return any(signer).(TransactionSigner), err + return any(signer).(types.TransactionSigner), err } */ } @@ -58,7 +68,7 @@ func initSigners() { func initSingleSignerPayloads() { TestSingleSignerPayloads = make(map[string]CreateSingleSignerPayload) TestSingleSignerPayloads["Entry Function"] = buildSingleSignerEntryFunction - TestSingleSignerPayloads["Script"] = buildSingleSignerScript + TestSingleSignerPayloads["types.Script"] = buildSingleSignerScript } func TestNamedConfig(t *testing.T) { @@ -86,7 +96,7 @@ func Test_SingleSignerFlows(t *testing.T) { } } -func setupIntegrationTest(t *testing.T, createAccount CreateSigner) (*Client, TransactionSigner) { +func setupIntegrationTest(t *testing.T, createAccount CreateSigner) (*Client, types.TransactionSigner) { // All of these run against localnet if testing.Short() { t.Skip("integration test expects network connection to localnet") @@ -212,9 +222,9 @@ func testTransactionSimulation(t *testing.T, createAccount CreateSigner, buildTr } func TestAPTTransferTransaction(t *testing.T) { - sender, err := NewEd25519Account() + sender, err := types.NewEd25519Account() assert.NoError(t, err) - dest, err := NewEd25519Account() + dest, err := types.NewEd25519Account() assert.NoError(t, err) client, err := createTestClient() @@ -234,7 +244,7 @@ func Test_Indexer(t *testing.T) { assert.NoError(t, err) // Fund account - account, err := NewEd25519Account() + account, err := types.NewEd25519Account() assert.NoError(t, err) err = client.Fund(account.AccountAddress(), 10) @@ -320,14 +330,14 @@ func Test_Block(t *testing.T) { func Test_Account(t *testing.T) { client, err := createTestClient() assert.NoError(t, err) - account, err := client.Account(AccountOne) + account, err := client.Account(types.AccountOne) assert.NoError(t, err) sequenceNumber, err := account.SequenceNumber() assert.NoError(t, err) assert.Equal(t, uint64(0), sequenceNumber) authKey, err := account.AuthenticationKey() assert.NoError(t, err) - assert.Equal(t, AccountOne[:], authKey[:]) + assert.Equal(t, types.AccountOne[:], authKey[:]) } func Test_Transactions(t *testing.T) { @@ -370,11 +380,11 @@ func Test_AccountResources(t *testing.T) { client, err := createTestClient() assert.NoError(t, err) - resources, err := client.AccountResources(AccountOne) + resources, err := client.AccountResources(types.AccountOne) assert.NoError(t, err) assert.Greater(t, len(resources), 0) - resourcesBcs, err := client.AccountResourcesBCS(AccountOne) + resourcesBcs, err := client.AccountResourcesBCS(types.AccountOne) assert.NoError(t, err) assert.Greater(t, len(resourcesBcs), 0) } @@ -418,9 +428,9 @@ func Test_Concurrent_Submission(t *testing.T) { client, err := createTestClient() assert.NoError(t, err) - account1, err := NewEd25519Account() + account1, err := types.NewEd25519Account() assert.NoError(t, err) - account2, err := NewEd25519Account() + account2, err := types.NewEd25519Account() assert.NoError(t, err) err = client.Fund(account1.AccountAddress(), 100_000_000) @@ -433,7 +443,7 @@ func Test_Concurrent_Submission(t *testing.T) { results := make(chan TransactionSubmissionResponse, 50) go client.BuildSignAndSubmitTransactions(account1, payloads, results, ExpirationSeconds(20)) - transferPayload, err := CoinTransferPayload(nil, AccountOne, 100) + transferPayload, err := types.CoinTransferPayload(nil, types.AccountOne, 100) assert.NoError(t, err) // Generate transactions @@ -441,7 +451,7 @@ func Test_Concurrent_Submission(t *testing.T) { payloads <- TransactionBuildPayload{ Id: i, Type: TransactionSubmissionTypeSingle, // TODO: not needed? - Inner: TransactionPayload{ + Inner: types.TransactionPayload{ Payload: transferPayload, }, } @@ -512,15 +522,15 @@ func TestClient_View(t *testing.T) { assert.NoError(t, err) payload := &ViewPayload{ - Module: ModuleId{Address: AccountOne, Name: "coin"}, + Module: types.ModuleId{Address: types.AccountOne, Name: "coin"}, Function: "balance", - ArgTypes: []TypeTag{AptosCoinTypeTag}, - Args: [][]byte{AccountOne[:]}, + ArgTypes: []types.TypeTag{types.AptosCoinTypeTag}, + Args: [][]byte{types.AccountOne[:]}, } vals, err := client.View(payload) assert.NoError(t, err) assert.Len(t, vals, 1) - _, err = StrToUint64(vals[0].(string)) + _, err = util.StrToUint64(vals[0].(string)) assert.NoError(t, err) } @@ -560,28 +570,28 @@ func TestClient_NodeAPIHealthCheck(t *testing.T) { }) } -func buildSingleSignerEntryFunction(client *Client, sender TransactionSigner, options ...any) (*RawTransaction, error) { - return APTTransferTransaction(client, sender, AccountOne, 100, options...) +func buildSingleSignerEntryFunction(client *Client, sender types.TransactionSigner, options ...any) (*types.RawTransaction, error) { + return APTTransferTransaction(client, sender, types.AccountOne, 100, options...) } -func buildSingleSignerScript(client *Client, sender TransactionSigner, options ...any) (*RawTransaction, error) { - scriptBytes, err := ParseHex(singleSignerScript) +func buildSingleSignerScript(client *Client, sender types.TransactionSigner, options ...any) (*types.RawTransaction, error) { + scriptBytes, err := util.ParseHex(singleSignerScript) if err != nil { return nil, err } amount := uint64(1) - dest := AccountOne + dest := types.AccountOne rawTxn, err := client.BuildTransaction(sender.AccountAddress(), - TransactionPayload{Payload: &Script{ + types.TransactionPayload{Payload: &types.Script{ Code: scriptBytes, - ArgTypes: []TypeTag{}, - Args: []ScriptArgument{{ - Variant: ScriptArgumentU64, + ArgTypes: []types.TypeTag{}, + Args: []types.ScriptArgument{{ + Variant: types.ScriptArgumentU64, Value: amount, }, { - Variant: ScriptArgumentAddress, + Variant: types.ScriptArgumentAddress, Value: dest, }}, }}, diff --git a/client_util.go b/client/client_util.go similarity index 75% rename from client_util.go rename to client/client_util.go index d96b12a..8233831 100644 --- a/client_util.go +++ b/client/client_util.go @@ -1,9 +1,11 @@ -package aptos +package client import ( "fmt" "net/url" "runtime/debug" + + "github.com/aptos-labs/aptos-go-sdk/types" ) // ClientHeader is the header key for the SDK version @@ -52,14 +54,14 @@ func init() { // Amount in Octas (10^-8 APT) // // options may be: MaxGasAmount, GasUnitPrice, ExpirationSeconds, ValidUntil, SequenceNumber, ChainIdOption -// deprecated, please use the EntryFunction APIs -func APTTransferTransaction(client *Client, sender TransactionSigner, dest AccountAddress, amount uint64, options ...any) (rawTxn *RawTransaction, err error) { - entryFunction, err := CoinTransferPayload(nil, dest, amount) +// deprecated, please use the types.EntryFunction APIs +func APTTransferTransaction(client *Client, sender types.TransactionSigner, dest types.AccountAddress, amount uint64, options ...any) (rawTxn *types.RawTransaction, err error) { + entryFunction, err := types.CoinTransferPayload(nil, dest, amount) if err != nil { return nil, err } rawTxn, err = client.BuildTransaction(sender.AccountAddress(), - TransactionPayload{Payload: entryFunction}, options...) + types.TransactionPayload{Payload: entryFunction}, options...) return } diff --git a/faucet.go b/client/faucet.go similarity index 91% rename from faucet.go rename to client/faucet.go index 95fb175..0c39ced 100644 --- a/faucet.go +++ b/client/faucet.go @@ -1,4 +1,4 @@ -package aptos +package client import ( "errors" @@ -6,6 +6,8 @@ import ( "log/slog" "net/url" "strconv" + + "github.com/aptos-labs/aptos-go-sdk/types" ) // FaucetClient uses the underlying NodeClient to request for APT for gas on a network. @@ -28,7 +30,7 @@ func NewFaucetClient(nodeClient *NodeClient, faucetUrl string) (*FaucetClient, e } // Fund account with the given amount of AptosCoin -func (faucetClient *FaucetClient) Fund(address AccountAddress, amount uint64) error { +func (faucetClient *FaucetClient) Fund(address types.AccountAddress, amount uint64) error { if faucetClient.nodeClient == nil { return errors.New("faucet's node-client not initialized") } diff --git a/fungible_asset_client.go b/client/fungible_asset_client.go similarity index 65% rename from fungible_asset_client.go rename to client/fungible_asset_client.go index e93edf8..725f3ba 100644 --- a/fungible_asset_client.go +++ b/client/fungible_asset_client.go @@ -1,23 +1,26 @@ -package aptos +package client import ( "errors" "math/big" "strconv" + + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/aptos-labs/aptos-go-sdk/util" ) // FungibleAssetClient This is an example client around a single fungible asset type FungibleAssetClient struct { - aptosClient *Client // Aptos client - metadataAddress *AccountAddress // Metadata address of the fungible asset + aptosClient *Client // Aptos client + metadataAddress *types.AccountAddress // Metadata address of the fungible asset } -// NewFungibleAssetClient verifies the [AccountAddress] of the metadata exists when creating the client +// NewFungibleAssetClient verifies the [types.AccountAddress] of the metadata exists when creating the client // // TODO: Add lookup of other metadata information such as symbol, supply, etc -func NewFungibleAssetClient(client *Client, metadataAddress *AccountAddress) (faClient *FungibleAssetClient, err error) { +func NewFungibleAssetClient(client *Client, metadataAddress *types.AccountAddress) (faClient *FungibleAssetClient, err error) { // Retrieve the Metadata resource to ensure the fungible asset actually exists - // TODO: all functions should take *AccountAddress + // TODO: all functions should take *types.AccountAddress _, err = client.AccountResource(*metadataAddress, "0x1::fungible_asset::Metadata") if err != nil { return @@ -33,14 +36,14 @@ func NewFungibleAssetClient(client *Client, metadataAddress *AccountAddress) (fa // -- Entry functions -- // // Transfer sends amount of the fungible asset from senderStore to receiverStore -func (client *FungibleAssetClient) Transfer(sender TransactionSigner, senderStore AccountAddress, receiverStore AccountAddress, amount uint64) (signedTxn *SignedTransaction, err error) { - payload, err := FungibleAssetTransferPayload(client.metadataAddress, senderStore, receiverStore, amount) +func (client *FungibleAssetClient) Transfer(sender types.TransactionSigner, senderStore types.AccountAddress, receiverStore types.AccountAddress, amount uint64) (signedTxn *types.SignedTransaction, err error) { + payload, err := types.FungibleAssetTransferPayload(client.metadataAddress, senderStore, receiverStore, amount) if err != nil { return nil, err } // Build transaction - rawTxn, err := client.aptosClient.BuildTransaction(sender.AccountAddress(), TransactionPayload{Payload: payload}) + rawTxn, err := client.aptosClient.BuildTransaction(sender.AccountAddress(), types.TransactionPayload{Payload: payload}) if err != nil { return } @@ -51,13 +54,13 @@ func (client *FungibleAssetClient) Transfer(sender TransactionSigner, senderStor } // TransferPrimaryStore sends amount of the fungible asset from the primary store of the sender to receiverAddress -func (client *FungibleAssetClient) TransferPrimaryStore(sender TransactionSigner, receiverAddress AccountAddress, amount uint64) (signedTxn *SignedTransaction, err error) { +func (client *FungibleAssetClient) TransferPrimaryStore(sender types.TransactionSigner, receiverAddress types.AccountAddress, amount uint64) (signedTxn *types.SignedTransaction, err error) { // Build transaction - payload, err := FungibleAssetPrimaryStoreTransferPayload(client.metadataAddress, receiverAddress, amount) + payload, err := types.FungibleAssetPrimaryStoreTransferPayload(client.metadataAddress, receiverAddress, amount) if err != nil { return nil, err } - rawTxn, err := client.aptosClient.BuildTransaction(sender.AccountAddress(), TransactionPayload{Payload: payload}) + rawTxn, err := client.aptosClient.BuildTransaction(sender.AccountAddress(), types.TransactionPayload{Payload: payload}) if err != nil { return } @@ -68,21 +71,21 @@ func (client *FungibleAssetClient) TransferPrimaryStore(sender TransactionSigner // -- View functions -- // -// PrimaryStoreAddress returns the [AccountAddress] of the primary store for the owner +// PrimaryStoreAddress returns the [types.AccountAddress] of the primary store for the owner // // Note that the primary store may not exist at the address. Use [FungibleAssetClient.PrimaryStoreExists] to check. -func (client *FungibleAssetClient) PrimaryStoreAddress(owner *AccountAddress) (address *AccountAddress, err error) { +func (client *FungibleAssetClient) PrimaryStoreAddress(owner *types.AccountAddress) (address *types.AccountAddress, err error) { val, err := client.viewPrimaryStoreMetadata([][]byte{owner[:], client.metadataAddress[:]}, "primary_store_address") if err != nil { return } - address = &AccountAddress{} + address = &types.AccountAddress{} err = address.ParseStringRelaxed(val.(string)) return } // PrimaryStoreExists returns true if the primary store for the owner exists -func (client *FungibleAssetClient) PrimaryStoreExists(owner *AccountAddress) (exists bool, err error) { +func (client *FungibleAssetClient) PrimaryStoreExists(owner *types.AccountAddress) (exists bool, err error) { val, err := client.viewPrimaryStoreMetadata([][]byte{owner[:], client.metadataAddress[:]}, "primary_store_exists") if err != nil { return @@ -93,17 +96,17 @@ func (client *FungibleAssetClient) PrimaryStoreExists(owner *AccountAddress) (ex } // PrimaryBalance returns the balance of the primary store for the owner -func (client *FungibleAssetClient) PrimaryBalance(owner *AccountAddress) (balance uint64, err error) { +func (client *FungibleAssetClient) PrimaryBalance(owner *types.AccountAddress) (balance uint64, err error) { val, err := client.viewPrimaryStoreMetadata([][]byte{owner[:], client.metadataAddress[:]}, "balance") if err != nil { return } balanceStr := val.(string) - return StrToUint64(balanceStr) + return util.StrToUint64(balanceStr) } // PrimaryIsFrozen returns true if the primary store for the owner is frozen -func (client *FungibleAssetClient) PrimaryIsFrozen(owner *AccountAddress) (isFrozen bool, err error) { +func (client *FungibleAssetClient) PrimaryIsFrozen(owner *types.AccountAddress) (isFrozen bool, err error) { val, err := client.viewPrimaryStore([][]byte{owner[:], client.metadataAddress[:]}, "is_frozen") if err != nil { return @@ -113,7 +116,7 @@ func (client *FungibleAssetClient) PrimaryIsFrozen(owner *AccountAddress) (isFro } // Balance returns the balance of the store -func (client *FungibleAssetClient) Balance(storeAddress *AccountAddress) (balance uint64, err error) { +func (client *FungibleAssetClient) Balance(storeAddress *types.AccountAddress) (balance uint64, err error) { val, err := client.viewStore([][]byte{storeAddress[:]}, "balance") if err != nil { return @@ -123,7 +126,7 @@ func (client *FungibleAssetClient) Balance(storeAddress *AccountAddress) (balanc } // IsFrozen returns true if the store is frozen -func (client *FungibleAssetClient) IsFrozen(storeAddress *AccountAddress) (isFrozen bool, err error) { +func (client *FungibleAssetClient) IsFrozen(storeAddress *types.AccountAddress) (isFrozen bool, err error) { val, err := client.viewStore([][]byte{storeAddress[:]}, "is_frozen") if err != nil { return @@ -133,14 +136,14 @@ func (client *FungibleAssetClient) IsFrozen(storeAddress *AccountAddress) (isFro } // StoreExists returns true if the store exists -func (client *FungibleAssetClient) StoreExists(storeAddress *AccountAddress) (exists bool, err error) { +func (client *FungibleAssetClient) StoreExists(storeAddress *types.AccountAddress) (exists bool, err error) { payload := &ViewPayload{ - Module: ModuleId{ - Address: AccountOne, + Module: types.ModuleId{ + Address: types.AccountOne, Name: "fungible_asset", }, Function: "store_exists", - ArgTypes: []TypeTag{}, + ArgTypes: []types.TypeTag{}, Args: [][]byte{storeAddress[:]}, } @@ -153,8 +156,8 @@ func (client *FungibleAssetClient) StoreExists(storeAddress *AccountAddress) (ex return } -// StoreMetadata returns the [AccountAddress] of the metadata for the store -func (client *FungibleAssetClient) StoreMetadata(storeAddress *AccountAddress) (metadataAddress *AccountAddress, err error) { +// StoreMetadata returns the [types.AccountAddress] of the metadata for the store +func (client *FungibleAssetClient) StoreMetadata(storeAddress *types.AccountAddress) (metadataAddress *types.AccountAddress, err error) { val, err := client.viewStore([][]byte{storeAddress[:]}, "store_metadata") if err != nil { return @@ -213,15 +216,15 @@ func (client *FungibleAssetClient) Decimals() (decimals uint8, err error) { // viewMetadata calls a view function on the fungible asset metadata func (client *FungibleAssetClient) viewMetadata(args [][]byte, functionName string) (result any, err error) { - structTag := &StructTag{Address: AccountOne, Module: "fungible_asset", Name: "Metadata"} - typeTag := TypeTag{Value: structTag} + structTag := &types.StructTag{Address: types.AccountOne, Module: "fungible_asset", Name: "Metadata"} + tt := types.TypeTag{Value: structTag} payload := &ViewPayload{ - Module: ModuleId{ - Address: AccountOne, + Module: types.ModuleId{ + Address: types.AccountOne, Name: "fungible_asset", }, Function: functionName, - ArgTypes: []TypeTag{typeTag}, + ArgTypes: []types.TypeTag{tt}, Args: args, } @@ -235,15 +238,15 @@ func (client *FungibleAssetClient) viewMetadata(args [][]byte, functionName stri // viewStore calls a view function on the fungible asset store func (client *FungibleAssetClient) viewStore(args [][]byte, functionName string) (result any, err error) { - structTag := &StructTag{Address: AccountOne, Module: "fungible_asset", Name: "FungibleStore"} - typeTag := TypeTag{Value: structTag} + structTag := &types.StructTag{Address: types.AccountOne, Module: "fungible_asset", Name: "FungibleStore"} + tt := types.TypeTag{Value: structTag} payload := &ViewPayload{ - Module: ModuleId{ - Address: AccountOne, + Module: types.ModuleId{ + Address: types.AccountOne, Name: "fungible_asset", }, Function: functionName, - ArgTypes: []TypeTag{typeTag}, + ArgTypes: []types.TypeTag{tt}, Args: args, } @@ -257,15 +260,15 @@ func (client *FungibleAssetClient) viewStore(args [][]byte, functionName string) // viewPrimaryStore calls a view function on the primary fungible asset store func (client *FungibleAssetClient) viewPrimaryStore(args [][]byte, functionName string) (result any, err error) { - structTag := &StructTag{Address: AccountOne, Module: "fungible_asset", Name: "FungibleStore"} - typeTag := TypeTag{Value: structTag} + structTag := &types.StructTag{Address: types.AccountOne, Module: "fungible_asset", Name: "FungibleStore"} + tt := types.TypeTag{Value: structTag} payload := &ViewPayload{ - Module: ModuleId{ - Address: AccountOne, + Module: types.ModuleId{ + Address: types.AccountOne, Name: "primary_fungible_store", }, Function: functionName, - ArgTypes: []TypeTag{typeTag}, + ArgTypes: []types.TypeTag{tt}, Args: args, } @@ -279,15 +282,15 @@ func (client *FungibleAssetClient) viewPrimaryStore(args [][]byte, functionName // viewPrimaryStoreMetadata calls a view function on the primary fungible asset store metadata func (client *FungibleAssetClient) viewPrimaryStoreMetadata(args [][]byte, functionName string) (result any, err error) { - structTag := &StructTag{Address: AccountOne, Module: "fungible_asset", Name: "Metadata"} - typeTag := TypeTag{Value: structTag} + structTag := &types.StructTag{Address: types.AccountOne, Module: "fungible_asset", Name: "Metadata"} + tt := types.TypeTag{Value: structTag} payload := &ViewPayload{ - Module: ModuleId{ - Address: AccountOne, + Module: types.ModuleId{ + Address: types.AccountOne, Name: "primary_fungible_store", }, Function: functionName, - ArgTypes: []TypeTag{typeTag}, + ArgTypes: []types.TypeTag{tt}, Args: args, } @@ -301,14 +304,14 @@ func (client *FungibleAssetClient) viewPrimaryStoreMetadata(args [][]byte, funct // Helper function to pull out the object address // TODO: Move to somewhere more useful -func unwrapObject(val any) (address *AccountAddress, err error) { +func unwrapObject(val any) (address *types.AccountAddress, err error) { inner, ok := val.(map[string]any) if !ok { err = errors.New("bad view return from node, could not unwrap object") return } addressString := inner["inner"].(string) - address = &AccountAddress{} + address = &types.AccountAddress{} err = address.ParseStringRelaxed(addressString) return } @@ -331,5 +334,5 @@ func unwrapAggregator(val any) (num *big.Int, err error) { return } - return StrToBigInt(numStr) + return util.StrToBigInt(numStr) } diff --git a/http.go b/client/http.go similarity index 99% rename from http.go rename to client/http.go index 6ade6f9..fd7afcb 100644 --- a/http.go +++ b/client/http.go @@ -1,4 +1,4 @@ -package aptos +package client import ( "fmt" diff --git a/indexerClient.go b/client/indexerClient.go similarity index 95% rename from indexerClient.go rename to client/indexerClient.go index a9f1007..f66dc65 100644 --- a/indexerClient.go +++ b/client/indexerClient.go @@ -1,11 +1,13 @@ -package aptos +package client import ( "context" "fmt" - "github.com/hasura/go-graphql-client" "net/http" "time" + + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/hasura/go-graphql-client" ) // -- Note: all query parameters must start with capital letters -- @@ -35,7 +37,7 @@ type CoinBalance struct { } // GetCoinBalances retrieve the coin balances for all coins owned by the address -func (ic *IndexerClient) GetCoinBalances(address AccountAddress) ([]CoinBalance, error) { +func (ic *IndexerClient) GetCoinBalances(address types.AccountAddress) ([]CoinBalance, error) { var out []CoinBalance var q struct { Current_coin_balances []struct { diff --git a/client/multisig.go b/client/multisig.go new file mode 100644 index 0000000..7b535c3 --- /dev/null +++ b/client/multisig.go @@ -0,0 +1,180 @@ +package client + +import ( + "github.com/aptos-labs/aptos-go-sdk/bcs" + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/aptos-labs/aptos-go-sdk/util" +) + +// FetchNextMultisigAddress retrieves the next multisig address to be created from the given account +func (client *Client) FetchNextMultisigAddress(address types.AccountAddress) (*types.AccountAddress, error) { + viewResponse, err := client.View(&ViewPayload{ + Module: types.ModuleId{ + Address: types.AccountOne, + Name: "multisig_account", + }, + Function: "get_next_multisig_account_address", + ArgTypes: []types.TypeTag{}, + Args: [][]byte{address[:]}, + }) + if err != nil { + return nil, err + } + multisigAddress := &types.AccountAddress{} + err = multisigAddress.ParseStringRelaxed(viewResponse[0].(string)) + if err != nil { + return nil, err + } + + return multisigAddress, nil +} + +// -- Multisig payloads -- + +// 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 MultisigCreateAccountPayload(requiredSigners uint64, additionalAddresses []types.AccountAddress, metadataKeys []string, metadataValues []byte) (*types.EntryFunction, error) { + // Serialize arguments + additionalOwners, err := bcs.SerializeSequenceOnly(additionalAddresses) + if err != nil { + return nil, err + } + + requiredSignersBytes, err := bcs.SerializeU64(requiredSigners) + if err != nil { + return nil, err + } + + // TODO: This is a little better than before, but maybe we make some of these ahead of time + metadataKeysBytes, err := bcs.SerializeSingle(func(ser *bcs.Serializer) { + bcs.SerializeSequenceWithFunction(metadataKeys, ser, func(ser *bcs.Serializer, item string) { + ser.WriteString(item) + }) + }) + if err != nil { + return nil, err + } + + return &types.EntryFunction{ + Module: types.ModuleId{ + Address: types.AccountOne, + Name: "multisig_account", + }, + Function: "create_with_owners", + ArgTypes: []types.TypeTag{}, + Args: [][]byte{ + additionalOwners, // Addresses of the other 2 in the 3 owners + requiredSignersBytes, // The number of required signatures 2-of-3 + metadataKeysBytes, // Metadata keys for any metadata you want to add to the account + metadataValues, // Values for the metadata added, must be BCS encoded + }}, nil +} + +// MultisigAddOwnerPayload creates a payload to add an owner from the multisig +func MultisigAddOwnerPayload(owner types.AccountAddress) *types.EntryFunction { + return multisigOwnerPayloadCommon("add_owner", owner) +} + +// MultisigRemoveOwnerPayload creates a payload to remove an owner from the multisig +func MultisigRemoveOwnerPayload(owner types.AccountAddress) *types.EntryFunction { + return multisigOwnerPayloadCommon("remove_owner", owner) +} + +// 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 MultisigChangeThresholdPayload(numSignaturesRequired uint64) (*types.EntryFunction, error) { + thresholdBytes, err := bcs.SerializeU64(numSignaturesRequired) + if err != nil { + return nil, err + } + return &types.EntryFunction{ + Module: types.ModuleId{Address: types.AccountOne, Name: "multisig_account"}, + Function: "update_signatures_required", + ArgTypes: []types.TypeTag{}, + Args: [][]byte{thresholdBytes}, + }, nil +} + +// MultisigCreatetypes.TransactionPayload creates a transaction to be voted upon in an on-chain multisig +// +// Note, this serializes an types.EntryFunction payload, and sends it as an argument in the transaction. If the +// entry function payload is large, use MultisigCreatetypes.TransactionPayloadWithHash. The advantage of this over the +// hash version, is visibility on-chain. +func MultisigCreateTransactionPayload(multisigAddress types.AccountAddress, payload *types.MultisigTransactionPayload) (*types.EntryFunction, error) { + payloadBytes, err := bcs.Serialize(payload) + if err != nil { + return nil, err + } + // Serialize and add the number of bytes in front + payloadBytes2, err := bcs.SerializeBytes(payloadBytes) + if err != nil { + return nil, err + } + return multisigTransactionCommon("create_transaction", multisigAddress, [][]byte{payloadBytes2}), nil +} + +// MultisigCreatetypes.TransactionPayloadWithHash creates a transaction to be voted upon in an on-chain multisig +// +// This differs from MultisigCreatetypes.TransactionPayload 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 MultisigCreateTransactionPayloadWithHash(multisigAddress types.AccountAddress, payload *types.MultisigTransactionPayload) (*types.EntryFunction, error) { + payloadBytes, err := bcs.Serialize(payload) + if err != nil { + return nil, err + } + hash := util.Sha3256Hash([][]byte{payloadBytes}) + + // Serialize and add the number of bytes in front + hashBytes, err := bcs.SerializeBytes(hash) + if err != nil { + return nil, err + } + return multisigTransactionCommon("create_transaction_with_hash", multisigAddress, [][]byte{hashBytes}), nil +} + +// MultisigApprovePayload generates a payload for approving a transaction on-chain. The caller must be an owner of the +// multisig +func MultisigApprovePayload(multisigAddress types.AccountAddress, transactionId uint64) (*types.EntryFunction, error) { + return multisigTransactionWithTransactionIdCommon("approve_transaction", multisigAddress, transactionId) +} + +// MultisigRejectPayload generates a payload for rejecting a transaction on-chain. The caller must be an owner of the +// multisig +func MultisigRejectPayload(multisigAddress types.AccountAddress, transactionId uint64) (*types.EntryFunction, error) { + return multisigTransactionWithTransactionIdCommon("reject_transaction", multisigAddress, transactionId) +} + +// multisigTransactionWithTransactionIdCommon is a helper for functions that take TransactionId +func multisigTransactionWithTransactionIdCommon(functionName string, multisigAddress types.AccountAddress, transactionId uint64) (*types.EntryFunction, error) { + transactionIdBytes, err := bcs.SerializeU64(transactionId) + if err != nil { + return nil, err + } + return multisigTransactionCommon(functionName, multisigAddress, [][]byte{transactionIdBytes}), nil +} + +// multisigOwnerPayloadCommon is a helper for owner based multisig operations +func multisigTransactionCommon(functionName string, multisigAddress types.AccountAddress, additionalArgs [][]byte) *types.EntryFunction { + return &types.EntryFunction{ + Module: types.ModuleId{ + Address: types.AccountOne, + Name: "multisig_account", + }, + Function: functionName, + ArgTypes: []types.TypeTag{}, + Args: append([][]byte{multisigAddress[:]}, additionalArgs...), + } +} + +// multisigOwnerPayloadCommon is a helper for owner based multisig operations +func multisigOwnerPayloadCommon(functionName string, owner types.AccountAddress) *types.EntryFunction { + return &types.EntryFunction{ + Module: types.ModuleId{Address: types.AccountOne, Name: "multisig_account"}, + Function: functionName, + ArgTypes: []types.TypeTag{}, + Args: [][]byte{owner[:]}, + } +} diff --git a/nodeClient.go b/client/nodeClient.go similarity index 90% rename from nodeClient.go rename to client/nodeClient.go index e59f6cc..4db2c0e 100644 --- a/nodeClient.go +++ b/client/nodeClient.go @@ -1,4 +1,4 @@ -package aptos +package client import ( "bytes" @@ -17,6 +17,8 @@ import ( "github.com/aptos-labs/aptos-go-sdk/api" "github.com/aptos-labs/aptos-go-sdk/bcs" "github.com/aptos-labs/aptos-go-sdk/crypto" + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/aptos-labs/aptos-go-sdk/util" ) const ( @@ -107,14 +109,14 @@ func (rc *NodeClient) Info() (info NodeInfo, err error) { // Account gets information about an account for a given address // // Optionally, a ledgerVersion can be given to get the account state at a specific ledger version -func (rc *NodeClient) Account(address AccountAddress, ledgerVersion ...uint64) (info AccountInfo, err error) { +func (rc *NodeClient) Account(address types.AccountAddress, ledgerVersion ...uint64) (info types.AccountInfo, err error) { au := rc.baseUrl.JoinPath("accounts", address.String()) if len(ledgerVersion) > 0 { params := url.Values{} params.Set("ledger_version", strconv.FormatUint(ledgerVersion[0], 10)) au.RawQuery = params.Encode() } - info, err = Get[AccountInfo](rc, au.String()) + info, err = Get[types.AccountInfo](rc, au.String()) if err != nil { return info, fmt.Errorf("get account info api err: %w", err) } @@ -125,7 +127,7 @@ func (rc *NodeClient) Account(address AccountAddress, ledgerVersion ...uint64) ( // Optionally, a ledgerVersion can be given to get the account state at a specific ledger version // // For fetching raw Move structs as BCS, See #AccountResourceBCS -func (rc *NodeClient) AccountResource(address AccountAddress, resourceType string, ledgerVersion ...uint64) (data map[string]any, err error) { +func (rc *NodeClient) AccountResource(address types.AccountAddress, resourceType string, ledgerVersion ...uint64) (data map[string]any, err error) { au := rc.baseUrl.JoinPath("accounts", address.String(), "resource", resourceType) // TODO: offer a list of known-good resourceType string constants if len(ledgerVersion) > 0 { @@ -140,26 +142,26 @@ func (rc *NodeClient) AccountResource(address AccountAddress, resourceType strin return data, nil } -// AccountResources fetches resources for an account into a JSON-like map[string]any in AccountResourceInfo.Data +// AccountResources fetches resources for an account into a JSON-like map[string]any in types.AccountResourceInfo.Data // Optionally, a ledgerVersion can be given to get the account state at a specific ledger version // For fetching raw Move structs as BCS, See #AccountResourcesBCS -func (rc *NodeClient) AccountResources(address AccountAddress, ledgerVersion ...uint64) (resources []AccountResourceInfo, err error) { +func (rc *NodeClient) AccountResources(address types.AccountAddress, ledgerVersion ...uint64) (resources []types.AccountResourceInfo, err error) { au := rc.baseUrl.JoinPath("accounts", address.String(), "resources") if len(ledgerVersion) > 0 { params := url.Values{} params.Set("ledger_version", strconv.FormatUint(ledgerVersion[0], 10)) au.RawQuery = params.Encode() } - resources, err = Get[[]AccountResourceInfo](rc, au.String()) + resources, err = Get[[]types.AccountResourceInfo](rc, au.String()) if err != nil { return nil, fmt.Errorf("get resources api err: %w", err) } return resources, err } -// AccountResourcesBCS fetches account resources as raw Move struct BCS blobs in AccountResourceRecord.Data []byte +// AccountResourcesBCS fetches account resources as raw Move struct BCS blobs in types.AccountResourceRecord.Data []byte // Optionally, a ledgerVersion can be given to get the account state at a specific ledger version -func (rc *NodeClient) AccountResourcesBCS(address AccountAddress, ledgerVersion ...uint64) (resources []AccountResourceRecord, err error) { +func (rc *NodeClient) AccountResourcesBCS(address types.AccountAddress, ledgerVersion ...uint64) (resources []types.AccountResourceRecord, err error) { au := rc.baseUrl.JoinPath("accounts", address.String(), "resources") if len(ledgerVersion) > 0 { params := url.Values{} @@ -173,7 +175,7 @@ func (rc *NodeClient) AccountResourcesBCS(address AccountAddress, ledgerVersion deserializer := bcs.NewDeserializer(blob) // See resource_test.go TestMoveResourceBCS - resources = bcs.DeserializeSequence[AccountResourceRecord](deserializer) + resources = bcs.DeserializeSequence[types.AccountResourceRecord](deserializer) return } @@ -460,7 +462,7 @@ func (rc *NodeClient) transactionsInner(start *uint64, limit *uint64) (data []*a } // SubmitTransaction submits a signed transaction to the network -func (rc *NodeClient) SubmitTransaction(signedTxn *SignedTransaction) (data *api.SubmitTransactionResponse, err error) { +func (rc *NodeClient) SubmitTransaction(signedTxn *types.SignedTransaction) (data *api.SubmitTransactionResponse, err error) { sblob, err := bcs.Serialize(signedTxn) if err != nil { return @@ -478,7 +480,7 @@ func (rc *NodeClient) SubmitTransaction(signedTxn *SignedTransaction) (data *api // // It will return the responses in the same order as the input transactions that failed. If the response is empty, then // all transactions succeeded. -func (rc *NodeClient) BatchSubmitTransaction(signedTxns []*SignedTransaction) (response *api.BatchSubmitTransactionResponse, err error) { +func (rc *NodeClient) BatchSubmitTransaction(signedTxns []*types.SignedTransaction) (response *api.BatchSubmitTransactionResponse, err error) { sblob, err := bcs.SerializeSequenceOnly(signedTxns) if err != nil { return @@ -503,9 +505,9 @@ type EstimatePrioritizedGasUnitPrice bool // SimulateTransaction simulates a transaction // -// TODO: This needs to support RawTransactionWithData +// TODO: This needs to support types.RawTransactionWithData // TODO: Support multikey simulation -func (rc *NodeClient) SimulateTransaction(rawTxn *RawTransaction, sender TransactionSigner, options ...any) (data []*api.UserTransaction, err error) { +func (rc *NodeClient) SimulateTransaction(rawTxn *types.RawTransaction, sender types.TransactionSigner, options ...any) (data []*api.UserTransaction, err error) { // build authenticator for simulation derivationScheme := sender.PubKey().Scheme() switch derivationScheme { @@ -579,10 +581,10 @@ type GasUnitPrice uint64 type ExpirationSeconds int64 // FeePayer will set the fee payer for a transaction -type FeePayer *AccountAddress +type FeePayer *types.AccountAddress // AdditionalSigners will set the additional signers for a transaction -type AdditionalSigners []AccountAddress +type AdditionalSigners []types.AccountAddress // SequenceNumber will set the sequence number for a transaction type SequenceNumber uint64 @@ -603,7 +605,7 @@ type ChainIdOption uint8 // - [ChainIdOption] // - [FeePayer] // - [AdditionalSigners] -func (rc *NodeClient) BuildTransaction(sender AccountAddress, payload TransactionPayload, options ...any) (rawTxn *RawTransaction, err error) { +func (rc *NodeClient) BuildTransaction(sender types.AccountAddress, payload types.TransactionPayload, options ...any) (rawTxn *types.RawTransaction, err error) { maxGasAmount := DefaultMaxGasAmount gasUnitPrice := DefaultGasUnitPrice @@ -654,7 +656,7 @@ func (rc *NodeClient) BuildTransaction(sender AccountAddress, payload Transactio // - [ChainIdOption] // - [FeePayer] // - [AdditionalSigners] -func (rc *NodeClient) BuildTransactionMultiAgent(sender AccountAddress, payload TransactionPayload, options ...any) (rawTxnImpl *RawTransactionWithData, err error) { +func (rc *NodeClient) BuildTransactionMultiAgent(sender types.AccountAddress, payload types.TransactionPayload, options ...any) (rawTxnImpl *types.RawTransactionWithData, err error) { maxGasAmount := DefaultMaxGasAmount gasUnitPrice := DefaultGasUnitPrice @@ -665,8 +667,8 @@ func (rc *NodeClient) BuildTransactionMultiAgent(sender AccountAddress, payload haveChainId := false haveGasUnitPrice := false - var feePayer *AccountAddress - var additionalSigners []AccountAddress + var feePayer *types.AccountAddress + var additionalSigners []types.AccountAddress for opti, option := range options { switch ovalue := option.(type) { @@ -705,18 +707,18 @@ func (rc *NodeClient) BuildTransactionMultiAgent(sender AccountAddress, payload // Based on the options, choose which to use if feePayer != nil { - return &RawTransactionWithData{ - Variant: MultiAgentWithFeePayerRawTransactionWithDataVariant, - Inner: &MultiAgentWithFeePayerRawTransactionWithData{ + return &types.RawTransactionWithData{ + Variant: types.MultiAgentWithFeePayerRawTransactionWithDataVariant, + Inner: &types.MultiAgentWithFeePayerRawTransactionWithData{ RawTxn: rawTxn, FeePayer: feePayer, SecondarySigners: additionalSigners, }, }, nil } else { - return &RawTransactionWithData{ - Variant: MultiAgentRawTransactionWithDataVariant, - Inner: &MultiAgentRawTransactionWithData{ + return &types.RawTransactionWithData{ + Variant: types.MultiAgentRawTransactionWithDataVariant, + Inner: &types.MultiAgentRawTransactionWithData{ RawTxn: rawTxn, SecondarySigners: additionalSigners, }, @@ -725,8 +727,8 @@ func (rc *NodeClient) BuildTransactionMultiAgent(sender AccountAddress, payload } func (rc *NodeClient) buildTransactionInner( - sender AccountAddress, - payload TransactionPayload, + sender types.AccountAddress, + payload types.TransactionPayload, maxGasAmount uint64, gasUnitPrice uint64, haveGasUnitPrice bool, @@ -735,7 +737,7 @@ func (rc *NodeClient) buildTransactionInner( haveSequenceNumber bool, chainId uint8, haveChainId bool, -) (rawTxn *RawTransaction, err error) { +) (rawTxn *types.RawTransaction, err error) { // Fetch requirements concurrently, and then consume them // Fetch GasUnitPrice which may be cached @@ -821,7 +823,7 @@ func (rc *NodeClient) buildTransactionInner( expirationTimestampSeconds := uint64(time.Now().Unix() + expirationSeconds) // Base raw transaction used for all requests - rawTxn = &RawTransaction{ + rawTxn = &types.RawTransaction{ Sender: sender, SequenceNumber: sequenceNumber, Payload: payload, @@ -835,10 +837,10 @@ func (rc *NodeClient) buildTransactionInner( // ViewPayload is a payload for a view function type ViewPayload struct { - Module ModuleId // ModuleId of the View function e.g. 0x1::coin - Function string // Name of the View function e.g. balance - ArgTypes []TypeTag // TypeTags of the type arguments - Args [][]byte // Arguments to the function encoded in BCS + Module types.ModuleId // types.ModuleId of the View function e.g. 0x1::coin + Function string // Name of the View function e.g. balance + ArgTypes []types.TypeTag // types.TypeTags of the type arguments + Args [][]byte // Arguments to the function encoded in BCS } func (vp *ViewPayload) MarshalBCS(ser *bcs.Serializer) { @@ -877,9 +879,9 @@ func (rc *NodeClient) View(payload *ViewPayload, ledgerVersion ...uint64) (data // EstimateGasPrice estimates the gas price given on-chain data // TODO: add caching for some period of time -func (rc *NodeClient) EstimateGasPrice() (info EstimateGasInfo, err error) { +func (rc *NodeClient) EstimateGasPrice() (info types.EstimateGasInfo, err error) { au := rc.baseUrl.JoinPath("estimate_gas_price") - info, err = Get[EstimateGasInfo](rc, au.String()) + info, err = Get[types.EstimateGasInfo](rc, au.String()) if err != nil { return info, fmt.Errorf("estimate gas price err: %w", err) } @@ -887,27 +889,27 @@ func (rc *NodeClient) EstimateGasPrice() (info EstimateGasInfo, err error) { } // AccountAPTBalance fetches the balance of an account of APT. Response is in octas or 1/10^8 APT. -func (rc *NodeClient) AccountAPTBalance(account AccountAddress) (balance uint64, err error) { +func (rc *NodeClient) AccountAPTBalance(account types.AccountAddress) (balance uint64, err error) { accountBytes, err := bcs.Serialize(&account) if err != nil { return 0, err } - values, err := rc.View(&ViewPayload{Module: ModuleId{ - Address: AccountOne, + values, err := rc.View(&ViewPayload{Module: types.ModuleId{ + Address: types.AccountOne, Name: "coin", }, Function: "balance", - ArgTypes: []TypeTag{AptosCoinTypeTag}, + ArgTypes: []types.TypeTag{types.AptosCoinTypeTag}, Args: [][]byte{accountBytes}, }) if err != nil { return 0, err } - return StrToUint64(values[0].(string)) + return util.StrToUint64(values[0].(string)) } // BuildSignAndSubmitTransaction builds, signs, and submits a transaction to the network -func (rc *NodeClient) BuildSignAndSubmitTransaction(sender TransactionSigner, payload TransactionPayload, options ...any) (data *api.SubmitTransactionResponse, err error) { +func (rc *NodeClient) BuildSignAndSubmitTransaction(sender types.TransactionSigner, payload types.TransactionPayload, options ...any) (data *api.SubmitTransactionResponse, err error) { rawTxn, err := rc.BuildTransaction(sender.AccountAddress(), payload, options...) if err != nil { return nil, err diff --git a/nodeClient_test.go b/client/nodeClient_test.go similarity index 97% rename from nodeClient_test.go rename to client/nodeClient_test.go index fa663bd..51ba4af 100644 --- a/nodeClient_test.go +++ b/client/nodeClient_test.go @@ -1,9 +1,10 @@ -package aptos +package client import ( - "github.com/stretchr/testify/assert" "testing" "time" + + "github.com/stretchr/testify/assert" ) func TestPollForTransaction(t *testing.T) { diff --git a/nodeInfo.go b/client/nodeInfo.go similarity index 99% rename from nodeInfo.go rename to client/nodeInfo.go index 160a32c..97ca0fe 100644 --- a/nodeInfo.go +++ b/client/nodeInfo.go @@ -1,4 +1,4 @@ -package aptos +package client import ( "log/slog" diff --git a/nodeInfo_test.go b/client/nodeInfo_test.go similarity index 99% rename from nodeInfo_test.go rename to client/nodeInfo_test.go index 08dc8c6..e159faa 100644 --- a/nodeInfo_test.go +++ b/client/nodeInfo_test.go @@ -1,12 +1,13 @@ -package aptos +package client import ( "bytes" "context" - "github.com/stretchr/testify/assert" "log/slog" "sync" "testing" + + "github.com/stretchr/testify/assert" ) type levelCounts struct { diff --git a/signer_test.go b/client/signer_test.go similarity index 94% rename from signer_test.go rename to client/signer_test.go index 7ebde19..ee4df9d 100644 --- a/signer_test.go +++ b/client/signer_test.go @@ -1,7 +1,8 @@ -package aptos +package client import ( "github.com/aptos-labs/aptos-go-sdk/crypto" + "github.com/aptos-labs/aptos-go-sdk/types" ) /* This is a collection of test signers, that don't make sense in the real world, but are used for testing */ @@ -27,8 +28,8 @@ func NewMultiEd25519Signer(numKeys uint8, signaturesRequired uint8) (*MultiEd255 }, nil } -func (s *MultiEd25519TestSigner) AccountAddress() AccountAddress { - address := AccountAddress{} +func (s *MultiEd25519TestSigner) AccountAddress() types.AccountAddress { + address := types.AccountAddress{} address.FromAuthKey(s.AuthKey()) return address } @@ -113,8 +114,8 @@ func NewMultiKeyTestSigner(numKeys uint8, signaturesRequired uint8) (*MultiKeyTe }, nil } -func (s *MultiKeyTestSigner) AccountAddress() AccountAddress { - address := AccountAddress{} +func (s *MultiKeyTestSigner) AccountAddress() types.AccountAddress { + address := types.AccountAddress{} address.FromAuthKey(s.AuthKey()) return address } diff --git a/spec_client_test.go b/client/spec_client_test.go similarity index 99% rename from spec_client_test.go rename to client/spec_client_test.go index 7dbd9db..bfedc38 100644 --- a/spec_client_test.go +++ b/client/spec_client_test.go @@ -1,8 +1,9 @@ -package aptos +package client import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) // Test_Spec_ClientConfig tests the client configuration diff --git a/transactionSubmission.go b/client/transactionSubmission.go similarity index 83% rename from transactionSubmission.go rename to client/transactionSubmission.go index e0f454d..abd6572 100644 --- a/transactionSubmission.go +++ b/client/transactionSubmission.go @@ -1,4 +1,4 @@ -package aptos +package client import ( "fmt" @@ -6,6 +6,7 @@ import ( "sync/atomic" "github.com/aptos-labs/aptos-go-sdk/api" + "github.com/aptos-labs/aptos-go-sdk/types" ) // TransactionSubmissionType is the counter for an enum @@ -21,18 +22,18 @@ const ( type TransactionBuildPayload struct { Id uint64 Type TransactionSubmissionType - Inner TransactionPayload // The actual transaction payload - Options []any // This is a placeholder to allow future optional arguments + Inner types.TransactionPayload // The actual transaction payload + Options []any // This is a placeholder to allow future optional arguments } type TransactionBuildResponse struct { Id uint64 - Response RawTransactionImpl + Response types.RawTransactionImpl Err error } type TransactionSubmissionRequest struct { Id uint64 - SignedTxn *SignedTransaction + SignedTxn *types.SignedTransaction } type TransactionSubmissionResponse struct { @@ -60,13 +61,13 @@ func (snt *SequenceNumberTracker) Update(next uint64) uint64 { return snt.SequenceNumber.Swap(next) } -// BuildTransactions start a goroutine to process [TransactionPayload] and spit out [RawTransactionImpl]. -func (client *Client) BuildTransactions(sender AccountAddress, payloads chan TransactionBuildPayload, responses chan TransactionBuildResponse, setSequenceNumber chan uint64, options ...any) (*RawTransaction, error) { +// BuildTransactions start a goroutine to process [types.TransactionPayload] and spit out [RawTransactionImpl]. +func (client *Client) BuildTransactions(sender types.AccountAddress, payloads chan TransactionBuildPayload, responses chan TransactionBuildResponse, setSequenceNumber chan uint64, options ...any) (*types.RawTransaction, error) { return client.BuildTransactions(sender, payloads, responses, setSequenceNumber, options...) } -// BuildTransactions start a goroutine to process [TransactionPayload] and spit out [RawTransactionImpl]. -func (rc *NodeClient) BuildTransactions(sender AccountAddress, payloads chan TransactionBuildPayload, responses chan TransactionBuildResponse, setSequenceNumber chan uint64, options ...any) { +// BuildTransactions start a goroutine to process [types.TransactionPayload] and spit out [RawTransactionImpl]. +func (rc *NodeClient) BuildTransactions(sender types.AccountAddress, payloads chan TransactionBuildPayload, responses chan TransactionBuildResponse, setSequenceNumber chan uint64, options ...any) { // Initialize state account, err := rc.Account(sender) if err != nil { @@ -148,7 +149,7 @@ func (rc *NodeClient) SubmitTransactions(requests chan TransactionSubmissionRequ func (rc *NodeClient) BatchSubmitTransactions(requests chan TransactionSubmissionRequest, responses chan TransactionSubmissionResponse) { defer close(responses) - inputs := make([]*SignedTransaction, 20) + inputs := make([]*types.SignedTransaction, 20) ids := make([]uint64, 20) i := uint32(0) @@ -195,7 +196,7 @@ func (rc *NodeClient) BatchSubmitTransactions(requests chan TransactionSubmissio // BuildSignAndSubmitTransactions starts up a goroutine to process transactions for a single [TransactionSender] // Closes output chan `responses` on completion of input chan `payloads`. func (client *Client) BuildSignAndSubmitTransactions( - sender TransactionSigner, + sender types.TransactionSigner, payloads chan TransactionBuildPayload, responses chan TransactionSubmissionResponse, buildOptions ...any, @@ -206,20 +207,20 @@ func (client *Client) BuildSignAndSubmitTransactions( // BuildSignAndSubmitTransactions starts up a goroutine to process transactions for a single [TransactionSender] // Closes output chan `responses` on completion of input chan `payloads`. func (rc *NodeClient) BuildSignAndSubmitTransactions( - sender TransactionSigner, + sender types.TransactionSigner, payloads chan TransactionBuildPayload, responses chan TransactionSubmissionResponse, buildOptions ...any, ) { - singleSigner := func(rawTxn RawTransactionImpl) (*SignedTransaction, error) { + singleSigner := func(rawTxn types.RawTransactionImpl) (*types.SignedTransaction, error) { switch rawTxn := rawTxn.(type) { - case *RawTransaction: + case *types.RawTransaction: return rawTxn.SignedTransaction(sender) - case *RawTransactionWithData: + case *types.RawTransactionWithData: switch rawTxn.Variant { - case MultiAgentRawTransactionWithDataVariant: + case types.MultiAgentRawTransactionWithDataVariant: return nil, fmt.Errorf("multi agent not supported, please provide a signer function") - case MultiAgentWithFeePayerRawTransactionWithDataVariant: + case types.MultiAgentWithFeePayerRawTransactionWithDataVariant: return nil, fmt.Errorf("fee payer not supported, please provide a signer function") default: return nil, fmt.Errorf("unsupported rawTransactionWithData type") @@ -247,18 +248,18 @@ func (rc *NodeClient) BuildSignAndSubmitTransactions( // func Example() { // client := NewNodeClient() // -// sender := NewEd25519Account() -// feePayer := NewEd25519Account() +// sender := types.NewEd25519Account() +// feePayer := types.NewEd25519Account() // // payloads := make(chan TransactionBuildPayload) // responses := make(chan TransactionSubmissionResponse) // -// signingFunc := func(rawTxn RawTransactionImpl) (*SignedTransaction, error) { +// signingFunc := func(rawTxn RawTransactionImpl) (*types.SignedTransaction, error) { // switch rawTxn.(type) { -// case *RawTransaction: +// case *types.RawTransaction: // return nil, fmt.Errorf("only fee payer supported") -// case *RawTransactionWithData: -// rawTxnWithData := rawTxn.(*RawTransactionWithData) +// case *types.RawTransactionWithData: +// rawTxnWithData := rawTxn.(*types.RawTransactionWithData) // switch rawTxnWithData.Variant { // case MultiAgentRawTransactionWithDataVariant: // return nil, fmt.Errorf("multi agent not supported, please provide a fee payer function") @@ -285,10 +286,10 @@ func (rc *NodeClient) BuildSignAndSubmitTransactions( // // } func (client *Client) BuildSignAndSubmitTransactionsWithSignFunction( - sender AccountAddress, + sender types.AccountAddress, payloads chan TransactionBuildPayload, responses chan TransactionSubmissionResponse, - sign func(rawTxn RawTransactionImpl) (*SignedTransaction, error), + sign func(rawTxn types.RawTransactionImpl) (*types.SignedTransaction, error), buildOptions ...any, ) { client.nodeClient.BuildSignAndSubmitTransactionsWithSignFunction( @@ -309,18 +310,18 @@ func (client *Client) BuildSignAndSubmitTransactionsWithSignFunction( // func Example() { // client := NewNodeClient() // -// sender := NewEd25519Account() -// feePayer := NewEd25519Account() +// sender := types.NewEd25519Account() +// feePayer := types.NewEd25519Account() // // payloads := make(chan TransactionBuildPayload) // responses := make(chan TransactionSubmissionResponse) // -// signingFunc := func(rawTxn RawTransactionImpl) (*SignedTransaction, error) { +// signingFunc := func(rawTxn RawTransactionImpl) (*types.SignedTransaction, error) { // switch rawTxn.(type) { -// case *RawTransaction: +// case *types.RawTransaction: // return nil, fmt.Errorf("only fee payer supported") -// case *RawTransactionWithData: -// rawTxnWithData := rawTxn.(*RawTransactionWithData) +// case *types.RawTransactionWithData: +// rawTxnWithData := rawTxn.(*types.RawTransactionWithData) // switch rawTxnWithData.Variant { // case MultiAgentRawTransactionWithDataVariant: // return nil, fmt.Errorf("multi agent not supported, please provide a fee payer function") @@ -347,10 +348,10 @@ func (client *Client) BuildSignAndSubmitTransactionsWithSignFunction( // // } func (rc *NodeClient) BuildSignAndSubmitTransactionsWithSignFunction( - sender AccountAddress, + sender types.AccountAddress, payloads chan TransactionBuildPayload, responses chan TransactionSubmissionResponse, - sign func(rawTxn RawTransactionImpl) (*SignedTransaction, error), + sign func(rawTxn types.RawTransactionImpl) (*types.SignedTransaction, error), buildOptions ...any, ) { // TODO: Make internal buffer size configurable with an optional parameter diff --git a/code_test.go b/code_test.go deleted file mode 100644 index fcd249a..0000000 --- a/code_test.go +++ /dev/null @@ -1 +0,0 @@ -package aptos diff --git a/examples/alternative_signing/main.go b/examples/alternative_signing/main.go index eb484c4..aa25f88 100644 --- a/examples/alternative_signing/main.go +++ b/examples/alternative_signing/main.go @@ -3,8 +3,10 @@ package main import ( "fmt" - "github.com/aptos-labs/aptos-go-sdk" + + "github.com/aptos-labs/aptos-go-sdk/client" "github.com/aptos-labs/aptos-go-sdk/crypto" + "github.com/aptos-labs/aptos-go-sdk/types" "golang.org/x/crypto/ed25519" ) @@ -71,8 +73,8 @@ func (signer *AlternativeSigner) AuthKey() *crypto.AuthenticationKey { return authKey } -func example(network aptos.NetworkConfig) { - client, err := aptos.NewClient(network) +func example(network client.NetworkConfig) { + aptosClient, err := client.NewClient(network) if err != nil { panic("Failed to create client:" + err.Error()) } @@ -84,17 +86,17 @@ func example(network aptos.NetworkConfig) { } // Create the sender from the key locally - sender, err := aptos.NewAccountFromSigner(signer) + sender, err := types.NewAccountFromSigner(signer) if err != nil { panic("Failed to create sender:" + err.Error()) } // Fund the sender with the faucet to create it on-chain - err = client.Fund(sender.Address, 100_000_000) + err = aptosClient.Fund(sender.Address, 100_000_000) fmt.Printf("We fund the signer account %s with the faucet\n", sender.Address.String()) // Prep arguments - receiver := aptos.AccountAddress{} + receiver := types.AccountAddress{} err = receiver.ParseStringRelaxed("0xBEEF") if err != nil { panic("Failed to parse address:" + err.Error()) @@ -102,7 +104,7 @@ func example(network aptos.NetworkConfig) { amount := uint64(100) // Build transaction - rawTxn, err := aptos.APTTransferTransaction(client, sender, receiver, amount) + rawTxn, err := client.APTTransferTransaction(aptosClient, sender, receiver, amount) if err != nil { panic("Failed to build transaction:" + err.Error()) } @@ -115,7 +117,7 @@ func example(network aptos.NetworkConfig) { fmt.Printf("Submit a coin transfer to address %s\n", receiver.String()) // Submit and wait for it to complete - submitResult, err := client.SubmitTransaction(signedTxn) + submitResult, err := aptosClient.SubmitTransaction(signedTxn) if err != nil { panic("Failed to submit transaction:" + err.Error()) } @@ -123,7 +125,7 @@ func example(network aptos.NetworkConfig) { // Wait for the transaction fmt.Printf("And we wait for the transaction %s to complete...\n", txnHash) - userTxn, err := client.WaitForTransaction(txnHash) + userTxn, err := aptosClient.WaitForTransaction(txnHash) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } @@ -132,5 +134,5 @@ func example(network aptos.NetworkConfig) { // main This example shows you how to make an alternative signer for the SDK, if you prefer a different library func main() { - example(aptos.DevnetConfig) + example(client.DevnetConfig) } diff --git a/examples/alternative_signing/main_test.go b/examples/alternative_signing/main_test.go index d03ec01..148c1b3 100644 --- a/examples/alternative_signing/main_test.go +++ b/examples/alternative_signing/main_test.go @@ -1,11 +1,12 @@ package main import ( - "github.com/aptos-labs/aptos-go-sdk" "testing" + + "github.com/aptos-labs/aptos-go-sdk/client" ) func Test_Main(t *testing.T) { t.Parallel() - example(aptos.LocalnetConfig) + example(client.LocalnetConfig) } diff --git a/examples/external_signing/main.go b/examples/external_signing/main.go index 1229ec1..ed198ed 100644 --- a/examples/external_signing/main.go +++ b/examples/external_signing/main.go @@ -3,8 +3,10 @@ package main import ( "fmt" - "github.com/aptos-labs/aptos-go-sdk" + + "github.com/aptos-labs/aptos-go-sdk/client" "github.com/aptos-labs/aptos-go-sdk/crypto" + "github.com/aptos-labs/aptos-go-sdk/types" "golang.org/x/crypto/ed25519" ) @@ -71,9 +73,9 @@ func (signer *ExternalSigner) AuthKey() *crypto.AuthenticationKey { return authKey } -func example(networkConfig aptos.NetworkConfig) { +func example(networkConfig client.NetworkConfig) { // Create a client for Aptos - client, err := aptos.NewClient(networkConfig) + aptosClient, err := client.NewClient(networkConfig) if err != nil { panic("Failed to create client:" + err.Error()) } @@ -85,31 +87,31 @@ func example(networkConfig aptos.NetworkConfig) { } // Create the sender from the key locally - sender, err := aptos.NewAccountFromSigner(signer) + sender, err := types.NewAccountFromSigner(signer) if err != nil { panic("Failed to create sender:" + err.Error()) } // Fund the sender with the faucet to create it on-chain - err = client.Fund(sender.Address, 100_000_000) + err = aptosClient.Fund(sender.Address, 100_000_000) fmt.Printf("We fund the signer account %s with the faucet\n", sender.Address.String()) // Prep arguments - receiver := aptos.AccountAddress{} + receiver := types.AccountAddress{} err = receiver.ParseStringRelaxed("0xBEEF") if err != nil { panic("Failed to parse address:" + err.Error()) } amount := uint64(100) - payload, err := aptos.CoinTransferPayload(nil, receiver, amount) + payload, err := types.CoinTransferPayload(nil, receiver, amount) if err != nil { panic("Failed to build payload:" + err.Error()) } // Sign transaction fmt.Printf("Submit a coin transfer to address %s\n", receiver.String()) - rawTxn, err := client.BuildTransaction(sender.Address, - aptos.TransactionPayload{Payload: payload}, + rawTxn, err := aptosClient.BuildTransaction(sender.Address, + types.TransactionPayload{Payload: payload}, ) if err != nil { panic("Failed to build raw transaction:" + err.Error()) @@ -139,7 +141,7 @@ func example(networkConfig aptos.NetworkConfig) { // TODO: Show how to send over a wire with an encoding // Submit and wait for it to complete - submitResult, err := client.SubmitTransaction(signedTxn) + submitResult, err := aptosClient.SubmitTransaction(signedTxn) if err != nil { panic("Failed to submit transaction:" + err.Error()) } @@ -147,7 +149,7 @@ func example(networkConfig aptos.NetworkConfig) { // Wait for the transaction fmt.Printf("And we wait for the transaction %s to complete...\n", txnHash) - userTxn, err := client.WaitForTransaction(txnHash) + userTxn, err := aptosClient.WaitForTransaction(txnHash) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } @@ -157,5 +159,5 @@ func example(networkConfig aptos.NetworkConfig) { // main This example shows you how to make an alternative signer for the SDK, if you prefer a different library func main() { - example(aptos.DevnetConfig) + example(client.DevnetConfig) } diff --git a/examples/external_signing/main_test.go b/examples/external_signing/main_test.go index d03ec01..16f90be 100644 --- a/examples/external_signing/main_test.go +++ b/examples/external_signing/main_test.go @@ -1,11 +1,10 @@ package main import ( - "github.com/aptos-labs/aptos-go-sdk" "testing" ) func Test_Main(t *testing.T) { t.Parallel() - example(aptos.LocalnetConfig) + example(types.LocalnetConfig) } diff --git a/examples/fungible_asset/main.go b/examples/fungible_asset/main.go index f2a704c..ca5e1d3 100644 --- a/examples/fungible_asset/main.go +++ b/examples/fungible_asset/main.go @@ -4,7 +4,7 @@ package main import ( "encoding/json" "fmt" - "github.com/aptos-labs/aptos-go-sdk" + "github.com/aptos-labs/aptos-go-sdk/bcs" "github.com/aptos-labs/aptos-go-sdk/crypto" ) @@ -15,9 +15,9 @@ const testEd25519PrivateKey = "0xc5338cd251c22daa8c9c9cc94f498cc8a5c7e1d2e75287a const metadata = "0x0572757065650100000000000000004038393534453933384132434137314536433445313139434230333341363036453341333537424245353843354430304235453132354236383238423745424331e7011f8b08000000000002ff3d8ecd6ec4200c84ef3cc58a7b13427ea9d4432f7d8928aa0c7636d136100149fbf885ed764ff68cbeb167dcc1dce04a13b3b0d1e5edc2fdb1137176920fabb3d9a90a5108cee0888bf32139e3c4d808889e42a030b17be4331b19173faa1f8cac6aa5846986bac6b9afda6648c350a3b06d4cdf2aec7487aa9648526ad960db894ee81e6609c0d379a49d2c92352b85e27d8f2e7cf8d4f0dbf9dbc4ae6bcc9f9618f7f05a96492e872e8cdb4ac8e4cb17e8f0588df3542480334f670e6db05a4b498743e37a6ffc476eeea472fe7ff2883f3567bf9aa419822b010000010572757065650000000300000000000000000000000000000000000000000000000000000000000000010e4170746f734672616d65776f726b00000000000000000000000000000000000000000000000000000000000000010b4170746f735374646c696200000000000000000000000000000000000000000000000000000000000000010a4d6f76655374646c696200" const bytecode = "0xa11ceb0b060000000c01000e020e30033e850104c3010605c901980107e102c30408a4074006e407950110f9088a010a830a120c950ae1020df60c060000010101020103010401050106000708000110060001120600011406000212060002170600011a0800021b07010001021e02000323070100000625070000080001000009010200000a030100000b030100000c000100000d040100000e05010005180302000219070200021c02090108021d0a0b010804080c0100021f0e0f000220101100022110120002221301000324011501000626161700042718010001281019000121101a000129101b00022a101c00040c1d0100042b1e0100042c1f010009080a08101403060c050300010501060c03060c050104060c050503030505050206050a02010806010b07010900020b070109000501010306080305030708030808080108050c0804080202060c0a0201080801060808010805010804010608040104010b09010900010a0201080a070608080b090104080a080a02080a080a010801010802010803010c030608010503030608020501040608020505030572757065650e66756e6769626c655f6173736574066f626a656374066f7074696f6e167072696d6172795f66756e6769626c655f73746f7265067369676e657206737472696e6709527570656552656673046275726e0a66615f616464726573730b696e69745f6d6f64756c650a696e697469616c697a65046d696e740a7365745f667265657a65087472616e73666572086d696e745f726566074d696e745265660c7472616e736665725f7265660b5472616e73666572526566086275726e5f726566074275726e526566106f626a5f7472616e736665725f7265660e6f626a5f657874656e645f72656609457874656e645265660a616464726573735f6f66156372656174655f6f626a6563745f61646472657373084d65746164617461064f626a65637411616464726573735f746f5f6f626a6563740869735f6f776e65720e436f6e7374727563746f72526566136372656174655f6e616d65645f6f626a6563741367656e65726174655f657874656e645f7265661567656e65726174655f7472616e736665725f7265661864697361626c655f756e67617465645f7472616e73666572064f7074696f6e046e6f6e6506537472696e6704757466382b6372656174655f7072696d6172795f73746f72655f656e61626c65645f66756e6769626c655f61737365741167656e65726174655f6d696e745f7265661167656e65726174655f6275726e5f7265660f67656e65726174655f7369676e65720f7365745f66726f7a656e5f666c6167117472616e736665725f776974685f726566978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aa0000000000000000000000000000000000000000000000000000000000000001030801000000000000000201020a02060552757065650a021413527570656573417265466f7254657374696e670a02060552555045450a023635697066733a2f2f516d585342534c6f337744426e6133314d4c56784b4a356f424a486b676f444d7845676a527a39745044665a506e0520978c213990c4833df71548df7ce49d54c759d6b6d932de22b24d56060b7af2aa0a020100126170746f733a3a6d657461646174615f7631760101000000000000000b455f4e4f545f4f574e45522a43616c6c6572206973206e6f74206f776e6572206f6620746865206d65746164617461206f626a6563740109527570656552656673010301183078313a3a6f626a6563743a3a4f626a65637447726f7570010a66615f616464726573730101000002050f08011108021308031508041608050000040100061a0b0011070c0507060c030e030703110838000b053801040d050f07002707060c040e04070311082b0010000b010b02110b0201010000020607060c000e0007031108020200000001030b00110302030000000d2d0b000703110c0c020e02110d0c040e02110e0c060e06110f0e02380207021111070411110701070511110707111111120e0211130c030e0211140c070e0211150c010e0211160c050e050b030b070b010b060b0412002d00020400040100061a0b0011070c0507060c030e030703110838000b053801040d050f07002707060c040e04070311082b0010010b010b021117020500040100061a0b0011070c0507060c030e030703110838000b053801040d050f07002707060c040e04070311082b0010020b010b021118020600040100061b0b0011070c0607060c040e040703110838000b063801040d050f07002707060c050e05070311082b0010020b010b020b0311190200020000000100" -func example(networkConfig aptos.NetworkConfig) { +func example(networkConfig client.NetworkConfig) { // Create a client for Aptos - client, err := aptos.NewClient(networkConfig) + aptosClient, err := client.NewClient(networkConfig) if err != nil { panic("Failed to create client:" + err.Error()) } @@ -28,7 +28,7 @@ func example(networkConfig aptos.NetworkConfig) { if err != nil { panic("Failed to decode Ed25519 private key:" + err.Error()) } - sender, err := aptos.NewAccountFromSigner(&key) + sender, err := types.NewAccountFromSigner(&key) if err != nil { panic("Failed to create sender:" + err.Error()) } @@ -40,9 +40,9 @@ func example(networkConfig aptos.NetworkConfig) { } // Publish the package for FA - metadataBytes, err := aptos.ParseHex(metadata) - bytecodeBytes, err := aptos.ParseHex(bytecode) - payload, err := aptos.PublishPackagePayloadFromJsonFile(metadataBytes, [][]byte{bytecodeBytes}) + metadataBytes, err := types.ParseHex(metadata) + bytecodeBytes, err := types.ParseHex(bytecode) + payload, err := types.PublishPackagePayloadFromJsonFile(metadataBytes, [][]byte{bytecodeBytes}) if err != nil { panic("Failed to create publish payload:" + err.Error()) } @@ -60,9 +60,9 @@ func example(networkConfig aptos.NetworkConfig) { } // Get the fungible asset address by view function - rupeeModule := aptos.ModuleId{Address: sender.Address, Name: "rupee"} - var noTypeTags []aptos.TypeTag - viewResponse, err := client.View(&aptos.ViewPayload{ + rupeeModule := types.ModuleId{Address: sender.Address, Name: "rupee"} + var noTypeTags []types.TypeTag + viewResponse, err := aptosClient.View(&types.ViewPayload{ Module: rupeeModule, Function: "fa_address", ArgTypes: noTypeTags, @@ -71,12 +71,12 @@ func example(networkConfig aptos.NetworkConfig) { if err != nil { panic("Failed to view fa address:" + err.Error()) } - faMetadataAddress := &aptos.AccountAddress{} + faMetadataAddress := &types.AccountAddress{} err = faMetadataAddress.ParseStringRelaxed(viewResponse[0].(string)) if err != nil { panic("Failed to parse fa address:" + err.Error()) } - faClient, err := aptos.NewFungibleAssetClient(client, faMetadataAddress) + faClient, err := client.NewFungibleAssetClient(client, faMetadataAddress) if err != nil { panic("Failed to create fungible asset client:" + err.Error()) } @@ -92,8 +92,8 @@ func example(networkConfig aptos.NetworkConfig) { panic("Failed to serialize amount:" + err.Error()) } serializedSenderAddress, _ := bcs.Serialize(&sender.Address) // This can't fail - response, err = client.BuildSignAndSubmitTransaction(sender, aptos.TransactionPayload{ - Payload: &aptos.EntryFunction{ + response, err = client.BuildSignAndSubmitTransaction(sender, types.TransactionPayload{ + Payload: &types.EntryFunction{ Module: rupeeModule, Function: "mint", ArgTypes: noTypeTags, @@ -116,7 +116,7 @@ func example(networkConfig aptos.NetworkConfig) { fmt.Printf("Before mint: %d, after mint: %d\n", beforeBalance, afterBalance) - receiver := &aptos.AccountAddress{} + receiver := &types.AccountAddress{} err = receiver.ParseStringRelaxed("0xCAFE") if err != nil { panic("Failed to parse receiver address:" + err.Error()) @@ -131,12 +131,12 @@ func example(networkConfig aptos.NetworkConfig) { if err != nil { panic("Failed to create primary store transfer transaction:" + err.Error()) } - response, err = client.SubmitTransaction(transferTxn) + response, err = aptosClient.SubmitTransaction(transferTxn) if err != nil { panic("Failed to submit transaction:" + err.Error()) } fmt.Printf("Submitted transfer as: %s\n", response.Hash) - err = client.PollForTransactions([]string{response.Hash}) + err = aptosClient.PollForTransactions([]string{response.Hash}) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } @@ -150,5 +150,5 @@ func example(networkConfig aptos.NetworkConfig) { // main This example shows how to create and transfer fungible assets func main() { - example(aptos.DevnetConfig) + example(client.DevnetConfig) } diff --git a/examples/fungible_asset/main_test.go b/examples/fungible_asset/main_test.go index d03ec01..16f90be 100644 --- a/examples/fungible_asset/main_test.go +++ b/examples/fungible_asset/main_test.go @@ -1,11 +1,10 @@ package main import ( - "github.com/aptos-labs/aptos-go-sdk" "testing" ) func Test_Main(t *testing.T) { t.Parallel() - example(aptos.LocalnetConfig) + example(types.LocalnetConfig) } diff --git a/examples/onchain_multisig/main.go b/examples/onchain_multisig/main.go index 238299e..7054e9c 100644 --- a/examples/onchain_multisig/main.go +++ b/examples/onchain_multisig/main.go @@ -4,28 +4,30 @@ package main import ( "encoding/json" "fmt" - "github.com/aptos-labs/aptos-go-sdk" + "time" + "github.com/aptos-labs/aptos-go-sdk/api" "github.com/aptos-labs/aptos-go-sdk/bcs" - "time" + "github.com/aptos-labs/aptos-go-sdk/client" + "github.com/aptos-labs/aptos-go-sdk/types" ) const TransferAmount = uint64(1_000_000) -func example(networkConfig aptos.NetworkConfig) { - client, err := aptos.NewClient(networkConfig) +func example(networkConfig client.NetworkConfig) { + aptosClient, err := client.NewClient(networkConfig) if err != nil { panic("Failed to create client " + err.Error()) } - recipient, err := aptos.NewEd25519Account() + recipient, err := types.NewEd25519Account() if err != nil { panic("Failed to create recipient " + err.Error()) } accounts := generateOwnerAccounts() // Fund owners - fundAccounts(client, []*aptos.AccountAddress{ + fundAccounts(aptosClient, []*types.AccountAddress{ &accounts[0].Address, &accounts[1].Address, &accounts[2].Address, @@ -34,47 +36,47 @@ func example(networkConfig aptos.NetworkConfig) { println(accounts[1].Address.String()) println(accounts[2].Address.String()) - multisigAddress := setUpMultisig(client, accounts) + multisigAddress := setUpMultisig(aptosClient, accounts) // Fund multisig println("Funding the multisig account...") - fundAccounts(client, []*aptos.AccountAddress{multisigAddress}) + fundAccounts(aptosClient, []*types.AccountAddress{multisigAddress}) // Run through flow with the full payload println("Creating a multisig transaction to transfer coins...") - payload := createMultisigTransferTransaction(client, accounts[1], *multisigAddress, recipient.Address) + payload := createMultisigTransferTransaction(aptosClient, accounts[1], *multisigAddress, recipient.Address) println("Owner 1 rejects but owner 3 approves.") - rejectAndApprove(client, *multisigAddress, accounts[0], accounts[2], 1) + rejectAndApprove(aptosClient, *multisigAddress, accounts[0], accounts[2], 1) println("Owner 2 can now execute the transfer transaction as it already has 2 approvals (from owners 2 and 3).") - executeTransaction(client, *multisigAddress, accounts[1], payload) + executeTransaction(aptosClient, *multisigAddress, accounts[1], payload) // Check balance of recipient, should be 1_000_000 - assertBalance(client, recipient.Address, TransferAmount) + assertBalance(aptosClient, recipient.Address, TransferAmount) println("Recipient's balance after transfer 1000000") // Run through flow with the full just a transaction hash println("Creating another multisig transaction using payload hash...") - payload = createMultisigTransferTransactionWithHash(client, accounts[1], *multisigAddress, recipient.Address) + payload = createMultisigTransferTransactionWithHash(aptosClient, accounts[1], *multisigAddress, recipient.Address) println("Owner 3 rejects but owner 1 approves.") - rejectAndApprove(client, *multisigAddress, accounts[2], accounts[0], 2) + rejectAndApprove(aptosClient, *multisigAddress, accounts[2], accounts[0], 2) println("Owner 1 can now execute the transfer with hash transaction as it already has 2 approvals (from owners 1 and 2).") - executeTransaction(client, *multisigAddress, accounts[0], payload) + executeTransaction(aptosClient, *multisigAddress, accounts[0], payload) // Check balance of recipient, should be 2_000_000 - assertBalance(client, recipient.Address, TransferAmount*2) + assertBalance(aptosClient, recipient.Address, TransferAmount*2) println("Recipient's balance after transfer 2000000") // Add an owner println("Adding an owner to the multisig account...") - payload = addOwnerTransaction(client, accounts[1], *multisigAddress, recipient.Address) + payload = addOwnerTransaction(aptosClient, accounts[1], *multisigAddress, recipient.Address) println("Owner 1 rejects but owner 3 approves.") - rejectAndApprove(client, *multisigAddress, accounts[0], accounts[2], 3) + rejectAndApprove(aptosClient, *multisigAddress, accounts[0], accounts[2], 3) println("Owner 2 can now execute the adding an owner transaction as it already has 2 approvals (from owners 1 and 3).") - userTxn := executeTransaction(client, *multisigAddress, accounts[1], payload) + userTxn := executeTransaction(aptosClient, *multisigAddress, accounts[1], payload) time.Sleep(time.Second) - _, owners := multisigResource(client, multisigAddress) + _, owners := multisigResource(aptosClient, multisigAddress) println("Number of Owners:", len(owners)) if len(owners) != 4 { @@ -83,13 +85,13 @@ func example(networkConfig aptos.NetworkConfig) { // Remove an owner println("Removing an owner from the multisig account...") - payload = removeOwnerTransaction(client, accounts[1], *multisigAddress, recipient.Address) + payload = removeOwnerTransaction(aptosClient, accounts[1], *multisigAddress, recipient.Address) println("Owner 1 rejects but owner 3 approves.") - rejectAndApprove(client, *multisigAddress, accounts[0], accounts[2], 4) + rejectAndApprove(aptosClient, *multisigAddress, accounts[0], accounts[2], 4) println("Owner 2 can now execute the removing an owner transaction as it already has 2 approvals (from owners 2 and 3).") - userTxn = executeTransaction(client, *multisigAddress, accounts[1], payload) + userTxn = executeTransaction(aptosClient, *multisigAddress, accounts[1], payload) - _, owners = multisigResource(client, multisigAddress) + _, owners = multisigResource(aptosClient, multisigAddress) println("Number of Owners:", len(owners)) if len(owners) != 3 { panic(fmt.Sprintf("Expected 3 owners got %d txn %s", len(owners), userTxn.Hash)) @@ -97,13 +99,13 @@ func example(networkConfig aptos.NetworkConfig) { // Change threshold println("Changing the signature threshold to 3-of-3...") - payload = changeThresholdTransaction(client, accounts[1], *multisigAddress, 3) + payload = changeThresholdTransaction(aptosClient, accounts[1], *multisigAddress, 3) println("Owner 1 rejects but owner 3 approves.") - rejectAndApprove(client, *multisigAddress, accounts[0], accounts[2], 5) + rejectAndApprove(aptosClient, *multisigAddress, accounts[0], accounts[2], 5) println("Owner 2 can now execute the change signature threshold transaction as it already has 2 approvals (from owners 2 and 3).") - userTxn = executeTransaction(client, *multisigAddress, accounts[1], payload) + userTxn = executeTransaction(aptosClient, *multisigAddress, accounts[1], payload) - threshold, _ := multisigResource(client, multisigAddress) + threshold, _ := multisigResource(aptosClient, multisigAddress) println("Signature Threshold: ", threshold) if threshold != 3 { panic(fmt.Sprintf("Expected 3-of-3 owners got %d-of-3 txn %s", threshold, userTxn.Hash)) @@ -111,7 +113,7 @@ func example(networkConfig aptos.NetworkConfig) { println("Multisig setup and transactions complete.") } -func assertBalance(client *aptos.Client, address aptos.AccountAddress, expectedBalance uint64) { +func assertBalance(client *client.Client, address types.AccountAddress, expectedBalance uint64) { amount, err := client.AccountAPTBalance(address) if err != nil { panic("failed to get balance: " + err.Error()) @@ -121,10 +123,10 @@ func assertBalance(client *aptos.Client, address aptos.AccountAddress, expectedB } } -func generateOwnerAccounts() []*aptos.Account { - accounts := make([]*aptos.Account, 3) +func generateOwnerAccounts() []*types.Account { + accounts := make([]*types.Account, 3) for i := 0; i < 3; i++ { - account, err := aptos.NewEd25519Account() + account, err := types.NewEd25519Account() if err != nil { panic("Failed to create account " + err.Error()) } @@ -133,7 +135,7 @@ func generateOwnerAccounts() []*aptos.Account { return accounts } -func fundAccounts(client *aptos.Client, accounts []*aptos.AccountAddress) { +func fundAccounts(client *client.Client, accounts []*types.AccountAddress) { for _, account := range accounts { err := client.Fund(*account, 100_000_000) if err != nil { @@ -142,7 +144,7 @@ func fundAccounts(client *aptos.Client, accounts []*aptos.AccountAddress) { } } -func setUpMultisig(client *aptos.Client, accounts []*aptos.Account) *aptos.AccountAddress { +func setUpMultisig(client *client.Client, accounts []*types.Account) *types.AccountAddress { println("Setting up a 2-of-3 multisig account...") // Step 1: Set up a 2-of-3 multisig account @@ -155,7 +157,7 @@ func setUpMultisig(client *aptos.Client, accounts []*aptos.Account) *aptos.Accou } // Create the multisig account with 3 owners and a signature threshold of 2. - createMultisig(client, accounts[0], []aptos.AccountAddress{accounts[1].Address, accounts[2].Address}) + createMultisig(client, accounts[0], []types.AccountAddress{accounts[1].Address, accounts[2].Address}) println("Multisig Account Address:", multisigAddress.String()) // should be 2 @@ -168,7 +170,7 @@ func setUpMultisig(client *aptos.Client, accounts []*aptos.Account) *aptos.Accou return multisigAddress } -func createMultisig(client *aptos.Client, account *aptos.Account, additionalAddresses []aptos.AccountAddress) { +func createMultisig(client *client.Client, account *types.Account, additionalAddresses []types.AccountAddress) { // TODO: Ideally, this would not be done, and the payload function would take an array of items to serialize metadataValue, err := bcs.SerializeSingle(func(ser *bcs.Serializer) { bcs.SerializeSequenceWithFunction([]string{"example"}, ser, func(ser *bcs.Serializer, item string) { @@ -178,7 +180,7 @@ func createMultisig(client *aptos.Client, account *aptos.Account, additionalAddr if err != nil { panic("Failed to serialize metadata value" + err.Error()) } - payload, err := aptos.MultisigCreateAccountPayload( + payload, err := types.MultisigCreateAccountPayload( 2, // Required signers additionalAddresses, // Other owners []string{"example"}, // Metadata keys @@ -192,7 +194,7 @@ func createMultisig(client *aptos.Client, account *aptos.Account, additionalAddr } // TODO: This should be a view function -func multisigResource(client *aptos.Client, multisigAddress *aptos.AccountAddress) (uint64, []any) { +func multisigResource(client *client.Client, multisigAddress *types.AccountAddress) (uint64, []any) { resource, err := client.AccountResource(*multisigAddress, "0x1::multisig_account::MultisigAccount") if err != nil { panic("Failed to get resource for multisig account: " + err.Error()) @@ -202,7 +204,7 @@ func multisigResource(client *aptos.Client, multisigAddress *aptos.AccountAddres numSigsRequiredStr := resourceData["num_signatures_required"].(string) - numSigsRequired, err := aptos.StrToUint64(numSigsRequiredStr) + numSigsRequired, err := types.StrToUint64(numSigsRequiredStr) if err != nil { panic("Failed to convert string to u64: " + err.Error()) } @@ -211,18 +213,18 @@ func multisigResource(client *aptos.Client, multisigAddress *aptos.AccountAddres return numSigsRequired, ownersArray } -func createMultisigTransferTransaction(client *aptos.Client, sender *aptos.Account, multisigAddress aptos.AccountAddress, recipient aptos.AccountAddress) *aptos.MultisigTransactionPayload { - entryFunctionPayload, err := aptos.CoinTransferPayload(nil, recipient, TransferAmount) +func createMultisigTransferTransaction(client *client.Client, sender *types.Account, multisigAddress types.AccountAddress, recipient types.AccountAddress) *types.MultisigTransactionPayload { + entryFunctionPayload, err := types.CoinTransferPayload(nil, recipient, TransferAmount) if err != nil { panic("Failed to create payload for multisig transfer: " + err.Error()) } - multisigPayload := &aptos.MultisigTransactionPayload{ - Variant: aptos.MultisigTransactionPayloadVariantEntryFunction, + multisigPayload := &types.MultisigTransactionPayload{ + Variant: types.MultisigTransactionPayloadVariantEntryFunction, Payload: entryFunctionPayload, } - createTransactionPayload, err := aptos.MultisigCreateTransactionPayload(multisigAddress, multisigPayload) + createTransactionPayload, err := types.MultisigCreateTransactionPayload(multisigAddress, multisigPayload) if err != nil { panic("Failed to create payload to create transaction for multisig transfer: " + err.Error()) } @@ -232,8 +234,8 @@ func createMultisigTransferTransaction(client *aptos.Client, sender *aptos.Accou return multisigPayload } -func createMultisigTransferTransactionWithHash(client *aptos.Client, sender *aptos.Account, multisigAddress aptos.AccountAddress, recipient aptos.AccountAddress) *aptos.MultisigTransactionPayload { - entryFunctionPayload, err := aptos.CoinTransferPayload(nil, recipient, 1_000_000) +func createMultisigTransferTransactionWithHash(client *client.Client, sender *types.Account, multisigAddress types.AccountAddress, recipient types.AccountAddress) *types.MultisigTransactionPayload { + entryFunctionPayload, err := types.CoinTransferPayload(nil, recipient, 1_000_000) if err != nil { panic("Failed to create payload for multisig transfer: " + err.Error()) } @@ -241,18 +243,18 @@ func createMultisigTransferTransactionWithHash(client *aptos.Client, sender *apt return createTransactionPayloadCommon(client, sender, multisigAddress, entryFunctionPayload) } -func addOwnerTransaction(client *aptos.Client, sender *aptos.Account, multisigAddress aptos.AccountAddress, newOwner aptos.AccountAddress) *aptos.MultisigTransactionPayload { - entryFunctionPayload := aptos.MultisigAddOwnerPayload(newOwner) +func addOwnerTransaction(client *client.Client, sender *types.Account, multisigAddress types.AccountAddress, newOwner types.AccountAddress) *types.MultisigTransactionPayload { + entryFunctionPayload := types.MultisigAddOwnerPayload(newOwner) return createTransactionPayloadCommon(client, sender, multisigAddress, entryFunctionPayload) } -func removeOwnerTransaction(client *aptos.Client, sender *aptos.Account, multisigAddress aptos.AccountAddress, removedOwner aptos.AccountAddress) *aptos.MultisigTransactionPayload { - entryFunctionPayload := aptos.MultisigRemoveOwnerPayload(removedOwner) +func removeOwnerTransaction(client *client.Client, sender *types.Account, multisigAddress types.AccountAddress, removedOwner types.AccountAddress) *types.MultisigTransactionPayload { + entryFunctionPayload := types.MultisigRemoveOwnerPayload(removedOwner) return createTransactionPayloadCommon(client, sender, multisigAddress, entryFunctionPayload) } -func changeThresholdTransaction(client *aptos.Client, sender *aptos.Account, multisigAddress aptos.AccountAddress, numSignaturesRequired uint64) *aptos.MultisigTransactionPayload { - entryFunctionPayload, err := aptos.MultisigChangeThresholdPayload(numSignaturesRequired) +func changeThresholdTransaction(client *client.Client, sender *types.Account, multisigAddress types.AccountAddress, numSignaturesRequired uint64) *types.MultisigTransactionPayload { + entryFunctionPayload, err := types.MultisigChangeThresholdPayload(numSignaturesRequired) if err != nil { panic("Failed to create payload for multisig remove owner: " + err.Error()) } @@ -260,13 +262,13 @@ func changeThresholdTransaction(client *aptos.Client, sender *aptos.Account, mul return createTransactionPayloadCommon(client, sender, multisigAddress, entryFunctionPayload) } -func createTransactionPayloadCommon(client *aptos.Client, sender *aptos.Account, multisigAddress aptos.AccountAddress, entryFunctionPayload *aptos.EntryFunction) *aptos.MultisigTransactionPayload { - multisigPayload := &aptos.MultisigTransactionPayload{ - Variant: aptos.MultisigTransactionPayloadVariantEntryFunction, +func createTransactionPayloadCommon(client *client.Client, sender *types.Account, multisigAddress types.AccountAddress, entryFunctionPayload *types.EntryFunction) *types.MultisigTransactionPayload { + multisigPayload := &types.MultisigTransactionPayload{ + Variant: types.MultisigTransactionPayloadVariantEntryFunction, Payload: entryFunctionPayload, } - createTransactionPayload, err := aptos.MultisigCreateTransactionPayloadWithHash(multisigAddress, multisigPayload) + createTransactionPayload, err := types.MultisigCreateTransactionPayloadWithHash(multisigAddress, multisigPayload) if err != nil { panic("Failed to create payload to create transaction for multisig: " + err.Error()) } @@ -276,14 +278,14 @@ func createTransactionPayloadCommon(client *aptos.Client, sender *aptos.Account, return multisigPayload } -func rejectAndApprove(client *aptos.Client, multisigAddress aptos.AccountAddress, rejector *aptos.Account, approver *aptos.Account, transactionId uint64) { - rejectPayload, err := aptos.MultisigRejectPayload(multisigAddress, transactionId) +func rejectAndApprove(client *client.Client, multisigAddress types.AccountAddress, rejector *types.Account, approver *types.Account, transactionId uint64) { + rejectPayload, err := types.MultisigRejectPayload(multisigAddress, transactionId) if err != nil { panic("Failed to build reject transaction payload: " + err.Error()) } submitAndWait(client, rejector, rejectPayload) - approvePayload, err := aptos.MultisigApprovePayload(multisigAddress, transactionId) + approvePayload, err := types.MultisigApprovePayload(multisigAddress, transactionId) if err != nil { panic("Failed to build approve transaction payload: " + err.Error()) } @@ -291,16 +293,16 @@ func rejectAndApprove(client *aptos.Client, multisigAddress aptos.AccountAddress submitAndWait(client, approver, approvePayload) } -func executeTransaction(client *aptos.Client, multisigAddress aptos.AccountAddress, sender *aptos.Account, payload *aptos.MultisigTransactionPayload) *api.UserTransaction { - executionPayload := &aptos.Multisig{ +func executeTransaction(client *client.Client, multisigAddress types.AccountAddress, sender *types.Account, payload *types.MultisigTransactionPayload) *api.UserTransaction { + executionPayload := &types.Multisig{ MultisigAddress: multisigAddress, Payload: payload, } return submitAndWait(client, sender, executionPayload) } -func submitAndWait(client *aptos.Client, sender *aptos.Account, payload aptos.TransactionPayloadImpl) *api.UserTransaction { - submitResponse, err := client.BuildSignAndSubmitTransaction(sender, aptos.TransactionPayload{Payload: payload}) +func submitAndWait(client *client.Client, sender *types.Account, payload types.TransactionPayloadImpl) *api.UserTransaction { + submitResponse, err := client.BuildSignAndSubmitTransaction(sender, types.TransactionPayload{Payload: payload}) if err != nil { panic("Failed to submit transaction: " + err.Error()) } @@ -327,5 +329,5 @@ func submitAndWait(client *aptos.Client, sender *aptos.Account, payload aptos.Tr } func main() { - example(aptos.DevnetConfig) + example(types.DevnetConfig) } diff --git a/examples/onchain_multisig/main_test.go b/examples/onchain_multisig/main_test.go index d03ec01..16f90be 100644 --- a/examples/onchain_multisig/main_test.go +++ b/examples/onchain_multisig/main_test.go @@ -1,11 +1,10 @@ package main import ( - "github.com/aptos-labs/aptos-go-sdk" "testing" ) func Test_Main(t *testing.T) { t.Parallel() - example(aptos.LocalnetConfig) + example(types.LocalnetConfig) } diff --git a/examples/performance_transaction/main.go b/examples/performance_transaction/main.go index 0a1b2a8..56f104f 100644 --- a/examples/performance_transaction/main.go +++ b/examples/performance_transaction/main.go @@ -3,25 +3,24 @@ package main import ( "encoding/json" - "github.com/aptos-labs/aptos-go-sdk" "time" ) // example This example shows you how to improve performance of the transaction submission // // Speed can be improved by locally handling the sequence number, gas price, and other factors -func example(networkConfig aptos.NetworkConfig) { +func example(networkConfig types.NetworkConfig) { start := time.Now() before := time.Now() // Create a client for Aptos - client, err := aptos.NewClient(networkConfig) + client, err := types.NewClient(networkConfig) if err != nil { panic("Failed to create client:" + err.Error()) } println("New client: ", time.Since(before).Milliseconds(), "ms") // Create a sender locally - sender, err := aptos.NewEd25519Account() + sender, err := types.NewEd25519Account() if err != nil { panic("Failed to create sender:" + err.Error()) } @@ -38,7 +37,7 @@ func example(networkConfig aptos.NetworkConfig) { before = time.Now() // Prep arguments - receiver := aptos.AccountAddress{} + receiver := types.AccountAddress{} err = receiver.ParseStringRelaxed("0xBEEF") if err != nil { panic("Failed to parse address:" + err.Error()) @@ -46,13 +45,13 @@ func example(networkConfig aptos.NetworkConfig) { amount := uint64(100) // Serialize arguments - payload, err := aptos.CoinTransferPayload(nil, receiver, amount) + payload, err := types.CoinTransferPayload(nil, receiver, amount) if err != nil { panic("Failed to serialize arguments:" + err.Error()) } rawTxn, err := client.BuildTransaction(sender.Address, - aptos.TransactionPayload{Payload: payload}, aptos.SequenceNumber(0)) // Use the sequence number to skip fetching it + types.TransactionPayload{Payload: payload}, types.SequenceNumber(0)) // Use the sequence number to skip fetching it if err != nil { panic("Failed to build transaction:" + err.Error()) } @@ -91,5 +90,5 @@ func example(networkConfig aptos.NetworkConfig) { } func main() { - example(aptos.DevnetConfig) + example(types.DevnetConfig) } diff --git a/examples/performance_transaction/main_test.go b/examples/performance_transaction/main_test.go index d03ec01..16f90be 100644 --- a/examples/performance_transaction/main_test.go +++ b/examples/performance_transaction/main_test.go @@ -1,11 +1,10 @@ package main import ( - "github.com/aptos-labs/aptos-go-sdk" "testing" ) func Test_Main(t *testing.T) { t.Parallel() - example(aptos.LocalnetConfig) + example(types.LocalnetConfig) } diff --git a/examples/sending_concurrent_transactions/main.go b/examples/sending_concurrent_transactions/main.go index 15356d1..512074d 100644 --- a/examples/sending_concurrent_transactions/main.go +++ b/examples/sending_concurrent_transactions/main.go @@ -2,18 +2,18 @@ package main import ( - "github.com/aptos-labs/aptos-go-sdk" - "github.com/aptos-labs/aptos-go-sdk/api" "time" + + "github.com/aptos-labs/aptos-go-sdk/api" ) -func setup(networkConfig aptos.NetworkConfig) (*aptos.Client, aptos.TransactionSigner) { - client, err := aptos.NewClient(networkConfig) +func setup(networkConfig types.NetworkConfig) (*types.Client, types.TransactionSigner) { + client, err := types.NewClient(networkConfig) if err != nil { panic("Failed to create client:" + err.Error()) } - sender, err := aptos.NewEd25519Account() + sender, err := types.NewEd25519Account() if err != nil { panic("Failed to create sender:" + err.Error()) } @@ -26,21 +26,21 @@ func setup(networkConfig aptos.NetworkConfig) (*aptos.Client, aptos.TransactionS return client, sender } -func payload() aptos.TransactionPayload { - receiver := aptos.AccountAddress{} +func payload() types.TransactionPayload { + receiver := types.AccountAddress{} err := receiver.ParseStringRelaxed("0xBEEF") if err != nil { panic("Failed to parse address:" + err.Error()) } amount := uint64(100) - p, err := aptos.CoinTransferPayload(nil, receiver, amount) + p, err := types.CoinTransferPayload(nil, receiver, amount) if err != nil { panic("Failed to serialize arguments:" + err.Error()) } - return aptos.TransactionPayload{Payload: p} + return types.TransactionPayload{Payload: p} } -func sendManyTransactionsSerially(networkConfig aptos.NetworkConfig, numTransactions uint64) { +func sendManyTransactionsSerially(networkConfig types.NetworkConfig, numTransactions uint64) { client, sender := setup(networkConfig) responses := make([]*api.SubmitTransactionResponse, numTransactions) @@ -49,7 +49,7 @@ func sendManyTransactionsSerially(networkConfig aptos.NetworkConfig, numTransact senderAddress := sender.AccountAddress() sequenceNumber := uint64(0) for i := uint64(0); i < numTransactions; i++ { - rawTxn, err := client.BuildTransaction(senderAddress, payload, aptos.SequenceNumber(sequenceNumber)) + rawTxn, err := client.BuildTransaction(senderAddress, payload, types.SequenceNumber(sequenceNumber)) if err != nil { panic("Failed to build transaction:" + err.Error()) } @@ -77,21 +77,21 @@ func sendManyTransactionsSerially(networkConfig aptos.NetworkConfig, numTransact } } -func sendManyTransactionsConcurrently(networkConfig aptos.NetworkConfig, numTransactions uint64) { +func sendManyTransactionsConcurrently(networkConfig types.NetworkConfig, numTransactions uint64) { client, sender := setup(networkConfig) payload := payload() // start submission goroutine - payloads := make(chan aptos.TransactionBuildPayload, 50) - results := make(chan aptos.TransactionSubmissionResponse, 50) + payloads := make(chan types.TransactionBuildPayload, 50) + results := make(chan types.TransactionSubmissionResponse, 50) go client.BuildSignAndSubmitTransactions(sender, payloads, results) // Submit transactions to goroutine go func() { for i := uint64(0); i < numTransactions; i++ { - payloads <- aptos.TransactionBuildPayload{ + payloads <- types.TransactionBuildPayload{ Id: i, - Type: aptos.TransactionSubmissionTypeSingle, + Type: types.TransactionSubmissionTypeSingle, Inner: payload, } } @@ -109,7 +109,7 @@ func sendManyTransactionsConcurrently(networkConfig aptos.NetworkConfig, numTran // example This example shows you how to improve performance of the transaction submission // // Speed can be improved by locally handling the sequence number, gas price, and other factors -func example(networkConfig aptos.NetworkConfig, numTransactions uint64) { +func example(networkConfig types.NetworkConfig, numTransactions uint64) { println("Sending", numTransactions, "transactions Serially") startSerial := time.Now() sendManyTransactionsSerially(networkConfig, numTransactions) @@ -126,5 +126,5 @@ func example(networkConfig aptos.NetworkConfig, numTransactions uint64) { } func main() { - example(aptos.DevnetConfig, 100) + example(types.DevnetConfig, 100) } diff --git a/examples/sending_concurrent_transactions/main_test.go b/examples/sending_concurrent_transactions/main_test.go index fe8b352..6cbc550 100644 --- a/examples/sending_concurrent_transactions/main_test.go +++ b/examples/sending_concurrent_transactions/main_test.go @@ -1,11 +1,10 @@ package main import ( - "github.com/aptos-labs/aptos-go-sdk" "testing" ) func Test_Main(t *testing.T) { t.Parallel() - example(aptos.LocalnetConfig, 100) + example(types.LocalnetConfig, 100) } diff --git a/examples/sponsored_transaction/main.go b/examples/sponsored_transaction/main.go index 8122d1a..2f0ff5e 100644 --- a/examples/sponsored_transaction/main.go +++ b/examples/sponsored_transaction/main.go @@ -4,7 +4,6 @@ package main import ( "fmt" - "github.com/aptos-labs/aptos-go-sdk" "github.com/aptos-labs/aptos-go-sdk/crypto" ) @@ -12,23 +11,23 @@ const FundAmount = 100_000_000 const TransferAmount = 1_000 // example This example shows you how to make an APT transfer transaction in the simplest possible way -func example(networkConfig aptos.NetworkConfig) { +func example(networkConfig types.NetworkConfig) { // Create a client for Aptos - client, err := aptos.NewClient(networkConfig) + client, err := types.NewClient(networkConfig) if err != nil { panic("Failed to create client:" + err.Error()) } // Create accounts locally for alice and bob - alice, err := aptos.NewEd25519Account() + alice, err := types.NewEd25519Account() if err != nil { panic("Failed to create alice:" + err.Error()) } - bob, err := aptos.NewEd25519Account() + bob, err := types.NewEd25519Account() if err != nil { panic("Failed to create bob:" + err.Error()) } - sponsor, err := aptos.NewEd25519Account() + sponsor, err := types.NewEd25519Account() if err != nil { panic("Failed to create sponsor:" + err.Error()) } @@ -68,16 +67,16 @@ func example(networkConfig aptos.NetworkConfig) { fmt.Printf("Sponsor: %d\n", sponsorBalance) // Build transaction - transferPayload, err := aptos.CoinTransferPayload(&aptos.AptosCoinTypeTag, bob.Address, TransferAmount) + transferPayload, err := types.CoinTransferPayload(&types.AptosCoinTypeTag, bob.Address, TransferAmount) if err != nil { panic("Failed to build transfer payload:" + err.Error()) } rawTxn, err := client.BuildTransactionMultiAgent( alice.Address, - aptos.TransactionPayload{ + types.TransactionPayload{ Payload: transferPayload, }, - aptos.FeePayer(&sponsor.Address), + types.FeePayer(&sponsor.Address), ) if err != nil { panic("Failed to build transaction:" + err.Error()) @@ -136,10 +135,10 @@ func example(networkConfig aptos.NetworkConfig) { rawTxn, err = client.BuildTransactionMultiAgent( alice.Address, - aptos.TransactionPayload{ + types.TransactionPayload{ Payload: transferPayload, }, - aptos.FeePayer(&aptos.AccountZero), // Note that the Address is 0x0, because we don't know the signer + types.FeePayer(&types.AccountZero), // Note that the Address is 0x0, because we don't know the signer ) if err != nil { panic("Failed to build transaction:" + err.Error()) @@ -204,5 +203,5 @@ func example(networkConfig aptos.NetworkConfig) { } func main() { - example(aptos.DevnetConfig) + example(types.DevnetConfig) } diff --git a/examples/sponsored_transaction/main_test.go b/examples/sponsored_transaction/main_test.go index d03ec01..16f90be 100644 --- a/examples/sponsored_transaction/main_test.go +++ b/examples/sponsored_transaction/main_test.go @@ -1,11 +1,10 @@ package main import ( - "github.com/aptos-labs/aptos-go-sdk" "testing" ) func Test_Main(t *testing.T) { t.Parallel() - example(aptos.LocalnetConfig) + example(types.LocalnetConfig) } diff --git a/examples/transfer_coin/main.go b/examples/transfer_coin/main.go index 2f9da4e..2efca0a 100644 --- a/examples/transfer_coin/main.go +++ b/examples/transfer_coin/main.go @@ -4,27 +4,28 @@ package main import ( "fmt" - "github.com/aptos-labs/aptos-go-sdk" "github.com/aptos-labs/aptos-go-sdk/bcs" + "github.com/aptos-labs/aptos-go-sdk/client" + "github.com/aptos-labs/aptos-go-sdk/types" ) const FundAmount = 100_000_000 const TransferAmount = 1_000 // example This example shows you how to make an APT transfer transaction in the simplest possible way -func example(networkConfig aptos.NetworkConfig) { +func example(networkConfig client.NetworkConfig) { // Create a client for Aptos - client, err := aptos.NewClient(networkConfig) + aptosClient, err := client.NewClient(networkConfig) if err != nil { panic("Failed to create client:" + err.Error()) } // Create accounts locally for alice and bob - alice, err := aptos.NewEd25519Account() + alice, err := types.NewEd25519Account() if err != nil { panic("Failed to create alice:" + err.Error()) } - bob, err := aptos.NewEd25519Account() + bob, err := types.NewEd25519Account() if err != nil { panic("Failed to create bob:" + err.Error()) } @@ -34,16 +35,16 @@ func example(networkConfig aptos.NetworkConfig) { fmt.Printf("Bob:%s\n", bob.Address.String()) // Fund the sender with the faucet to create it on-chain - err = client.Fund(alice.Address, FundAmount) + err = aptosClient.Fund(alice.Address, FundAmount) if err != nil { panic("Failed to fund alice:" + err.Error()) } - aliceBalance, err := client.AccountAPTBalance(alice.Address) + aliceBalance, err := aptosClient.AccountAPTBalance(alice.Address) if err != nil { panic("Failed to retrieve alice balance:" + err.Error()) } - bobBalance, err := client.AccountAPTBalance(bob.Address) + bobBalance, err := aptosClient.AccountAPTBalance(bob.Address) if err != nil { panic("Failed to retrieve bob balance:" + err.Error()) } @@ -52,7 +53,7 @@ func example(networkConfig aptos.NetworkConfig) { fmt.Printf("Bob:%d\n", bobBalance) // Build transaction - rawTxn, err := aptos.APTTransferTransaction(client, alice, bob.Address, TransferAmount) + rawTxn, err := client.APTTransferTransaction(aptosClient, alice, bob.Address, TransferAmount) if err != nil { panic("Failed to build transaction:" + err.Error()) } @@ -64,22 +65,22 @@ func example(networkConfig aptos.NetworkConfig) { } // Submit and wait for it to complete - submitResult, err := client.SubmitTransaction(signedTxn) + submitResult, err := aptosClient.SubmitTransaction(signedTxn) if err != nil { panic("Failed to submit transaction:" + err.Error()) } txnHash := submitResult.Hash // Wait for the transaction - _, err = client.WaitForTransaction(txnHash) + _, err = aptosClient.WaitForTransaction(txnHash) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } - aliceBalance, err = client.AccountAPTBalance(alice.Address) + aliceBalance, err = aptosClient.AccountAPTBalance(alice.Address) if err != nil { panic("Failed to retrieve alice balance:" + err.Error()) } - bobBalance, err = client.AccountAPTBalance(bob.Address) + bobBalance, err = aptosClient.AccountAPTBalance(bob.Address) if err != nil { panic("Failed to retrieve bob balance:" + err.Error()) } @@ -98,14 +99,14 @@ func example(networkConfig aptos.NetworkConfig) { panic("Failed to serialize transfer amount:" + err.Error()) } - resp, err := client.BuildSignAndSubmitTransaction(alice, aptos.TransactionPayload{ - Payload: &aptos.EntryFunction{ - Module: aptos.ModuleId{ - Address: aptos.AccountOne, + resp, err := aptosClient.BuildSignAndSubmitTransaction(alice, types.TransactionPayload{ + Payload: &types.EntryFunction{ + Module: types.ModuleId{ + Address: types.AccountOne, Name: "aptos_account", }, Function: "transfer", - ArgTypes: []aptos.TypeTag{}, + ArgTypes: []types.TypeTag{}, Args: [][]byte{ accountBytes, amountBytes, @@ -116,16 +117,16 @@ func example(networkConfig aptos.NetworkConfig) { panic("Failed to sign transaction:" + err.Error()) } - _, err = client.WaitForTransaction(resp.Hash) + _, err = aptosClient.WaitForTransaction(resp.Hash) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } - aliceBalance, err = client.AccountAPTBalance(alice.Address) + aliceBalance, err = aptosClient.AccountAPTBalance(alice.Address) if err != nil { panic("Failed to retrieve alice balance:" + err.Error()) } - bobBalance, err = client.AccountAPTBalance(bob.Address) + bobBalance, err = aptosClient.AccountAPTBalance(bob.Address) if err != nil { panic("Failed to retrieve bob balance:" + err.Error()) } @@ -135,5 +136,5 @@ func example(networkConfig aptos.NetworkConfig) { } func main() { - example(aptos.DevnetConfig) + example(client.DevnetConfig) } diff --git a/examples/transfer_coin/main_test.go b/examples/transfer_coin/main_test.go index d03ec01..148c1b3 100644 --- a/examples/transfer_coin/main_test.go +++ b/examples/transfer_coin/main_test.go @@ -1,11 +1,12 @@ package main import ( - "github.com/aptos-labs/aptos-go-sdk" "testing" + + "github.com/aptos-labs/aptos-go-sdk/client" ) func Test_Main(t *testing.T) { t.Parallel() - example(aptos.LocalnetConfig) + example(client.LocalnetConfig) } diff --git a/spec_bcs_test.go b/spec_bcs_test.go index 0e1f269..1981e2c 100644 --- a/spec_bcs_test.go +++ b/spec_bcs_test.go @@ -2,11 +2,13 @@ package aptos import ( "fmt" - "github.com/aptos-labs/aptos-go-sdk/bcs" - "github.com/stretchr/testify/assert" "math/big" "slices" "testing" + + "github.com/aptos-labs/aptos-go-sdk/bcs" + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/stretchr/testify/assert" ) type testStruct struct { @@ -17,7 +19,7 @@ type testStruct struct { u64 uint64 u128 big.Int u256 big.Int - address *AccountAddress + address *types.AccountAddress bytes []byte } @@ -41,7 +43,7 @@ func (st *testStruct) UnmarshalBCS(des *bcs.Deserializer) { st.u64 = des.U64() st.u128 = des.U128() st.u256 = des.U256() - st.address = &AccountAddress{} + st.address = &types.AccountAddress{} des.Struct(st.address) st.bytes = des.ReadBytes() // Custom error @@ -732,7 +734,7 @@ func Test_Spec_BCS_Struct(t *testing.T) { u64: 1, u128: *big.NewInt(1), u256: *big.NewInt(1), - address: &AccountOne, + address: &types.AccountOne, bytes: []byte{0x01, 0x00, 0x00}, }, { @@ -743,7 +745,7 @@ func Test_Spec_BCS_Struct(t *testing.T) { u64: 1, u128: *big.NewInt(1), u256: *big.NewInt(1), - address: &AccountOne, + address: &types.AccountOne, bytes: []byte{0x01, 0x00, 0x00}, }, } diff --git a/types/account.go b/types/account.go index 7db9229..c483619 100644 --- a/types/account.go +++ b/types/account.go @@ -3,8 +3,9 @@ package types import ( "encoding/hex" "errors" - "github.com/aptos-labs/aptos-go-sdk/crypto" "strings" + + "github.com/aptos-labs/aptos-go-sdk/crypto" ) // Account represents an on-chain account, with an associated signer, which must be a [crypto.Signer] diff --git a/accountInfo.go b/types/accountInfo.go similarity index 97% rename from accountInfo.go rename to types/accountInfo.go index bef48fc..988300b 100644 --- a/accountInfo.go +++ b/types/accountInfo.go @@ -1,4 +1,4 @@ -package aptos +package types import ( "encoding/hex" diff --git a/accountResourceInfo.go b/types/accountResourceInfo.go similarity index 95% rename from accountResourceInfo.go rename to types/accountResourceInfo.go index 864a227..ad1fedc 100644 --- a/accountResourceInfo.go +++ b/types/accountResourceInfo.go @@ -1,4 +1,4 @@ -package aptos +package types // AccountResourceInfo is returned by #AccountResource() and #AccountResources() type AccountResourceInfo struct { diff --git a/accountResourceRecord.go b/types/accountResourceRecord.go similarity index 97% rename from accountResourceRecord.go rename to types/accountResourceRecord.go index 7346e8a..6404e53 100644 --- a/accountResourceRecord.go +++ b/types/accountResourceRecord.go @@ -1,4 +1,4 @@ -package aptos +package types import ( "github.com/aptos-labs/aptos-go-sdk/bcs" diff --git a/code.go b/types/code.go similarity index 98% rename from code.go rename to types/code.go index f2b4e85..2c08205 100644 --- a/code.go +++ b/types/code.go @@ -1,4 +1,4 @@ -package aptos +package types import ( "github.com/aptos-labs/aptos-go-sdk/bcs" diff --git a/types/code_test.go b/types/code_test.go new file mode 100644 index 0000000..ab1254f --- /dev/null +++ b/types/code_test.go @@ -0,0 +1 @@ +package types diff --git a/coinPayloads.go b/types/coinPayloads.go similarity index 97% rename from coinPayloads.go rename to types/coinPayloads.go index c223f20..e8f98ac 100644 --- a/coinPayloads.go +++ b/types/coinPayloads.go @@ -1,6 +1,8 @@ -package aptos +package types -import "github.com/aptos-labs/aptos-go-sdk/bcs" +import ( + "github.com/aptos-labs/aptos-go-sdk/bcs" +) // CoinTransferPayload builds an EntryFunction payload for transferring coins // diff --git a/commonPayloads.go b/types/commonPayloads.go similarity index 99% rename from commonPayloads.go rename to types/commonPayloads.go index 3a0e1bb..ec34e57 100644 --- a/commonPayloads.go +++ b/types/commonPayloads.go @@ -1,7 +1,8 @@ -package aptos +package types import ( "errors" + "github.com/aptos-labs/aptos-go-sdk/bcs" ) diff --git a/estimateGasInfo.go b/types/estimateGasInfo.go similarity index 97% rename from estimateGasInfo.go rename to types/estimateGasInfo.go index 77b1aa3..4c3bb71 100644 --- a/estimateGasInfo.go +++ b/types/estimateGasInfo.go @@ -1,4 +1,4 @@ -package aptos +package types // EstimateGasInfo is returned by #EstimateGasPrice() type EstimateGasInfo struct { diff --git a/fungible_asset_client_test.go b/types/fungible_asset_client_test.go similarity index 89% rename from fungible_asset_client_test.go rename to types/fungible_asset_client_test.go index 4d799a4..b74bc23 100644 --- a/fungible_asset_client_test.go +++ b/types/fungible_asset_client_test.go @@ -1,4 +1,4 @@ -package aptos +package types /* TODO: Re-enable when running on localnet func TestClient(t *testing.T) { @@ -12,16 +12,16 @@ func TestClient(t *testing.T) { // Owner address ownerAddress := AccountAddress{} - err = ownerAddress.ParseStringRelaxed(types.defaultOwner) + err = ownerAddress.ParseStringRelaxed(defaultOwner) assert.NoError(t, err) // TODO: This flow seems awkward and I made mistakes by running Parse on the same address multiple times metadataAddress := AccountAddress{} - err = metadataAddress.ParseStringRelaxed(types.defaultMetadata) + err = metadataAddress.ParseStringRelaxed(defaultMetadata) assert.NoError(t, err) primaryStoreAddress := AccountAddress{} - err = primaryStoreAddress.ParseStringRelaxed(types.defaultStore) + err = primaryStoreAddress.ParseStringRelaxed(defaultStore) assert.NoError(t, err) // Create a fungible asset client @@ -53,7 +53,7 @@ func TestClient(t *testing.T) { assert.True(t, storeExists) // This should hold - storeNotExist, err := faClient.StoreExists(types.AccountOne) + storeNotExist, err := faClient.StoreExists(AccountOne) assert.NoError(t, err) assert.False(t, storeNotExist) diff --git a/moduleId.go b/types/moduleId.go similarity index 96% rename from moduleId.go rename to types/moduleId.go index e7dd1b0..9145784 100644 --- a/moduleId.go +++ b/types/moduleId.go @@ -1,4 +1,4 @@ -package aptos +package types import ( "github.com/aptos-labs/aptos-go-sdk/bcs" diff --git a/multisig.go b/types/multisig.go similarity index 88% rename from multisig.go rename to types/multisig.go index 85892df..a1c00b3 100644 --- a/multisig.go +++ b/types/multisig.go @@ -1,29 +1,9 @@ -package aptos +package types -import "github.com/aptos-labs/aptos-go-sdk/bcs" - -// FetchNextMultisigAddress retrieves the next multisig address to be created from the given account -func (client *Client) FetchNextMultisigAddress(address AccountAddress) (*AccountAddress, error) { - viewResponse, err := client.View(&ViewPayload{ - Module: ModuleId{ - Address: AccountOne, - Name: "multisig_account", - }, - Function: "get_next_multisig_account_address", - ArgTypes: []TypeTag{}, - Args: [][]byte{address[:]}, - }) - if err != nil { - return nil, err - } - multisigAddress := &AccountAddress{} - err = multisigAddress.ParseStringRelaxed(viewResponse[0].(string)) - if err != nil { - return nil, err - } - - return multisigAddress, nil -} +import ( + "github.com/aptos-labs/aptos-go-sdk/bcs" + "github.com/aptos-labs/aptos-go-sdk/util" +) // -- Multisig payloads -- @@ -121,7 +101,7 @@ func MultisigCreateTransactionPayloadWithHash(multisigAddress AccountAddress, pa if err != nil { return nil, err } - hash := Sha3256Hash([][]byte{payloadBytes}) + hash := util.Sha3256Hash([][]byte{payloadBytes}) // Serialize and add the number of bytes in front hashBytes, err := bcs.SerializeBytes(hash) diff --git a/rawTransaction.go b/types/rawTransaction.go similarity index 99% rename from rawTransaction.go rename to types/rawTransaction.go index 0fd7a20..0f9d882 100644 --- a/rawTransaction.go +++ b/types/rawTransaction.go @@ -1,7 +1,8 @@ -package aptos +package types import ( "fmt" + "github.com/aptos-labs/aptos-go-sdk/bcs" "github.com/aptos-labs/aptos-go-sdk/crypto" "golang.org/x/crypto/sha3" diff --git a/resource_test.go b/types/resource_test.go similarity index 99% rename from resource_test.go rename to types/resource_test.go index 7623d3d..ea4f21c 100644 --- a/resource_test.go +++ b/types/resource_test.go @@ -1,12 +1,13 @@ -package aptos +package types import ( "encoding/base64" - "github.com/aptos-labs/aptos-go-sdk/bcs" - "github.com/stretchr/testify/assert" "io" "strings" "testing" + + "github.com/aptos-labs/aptos-go-sdk/bcs" + "github.com/stretchr/testify/assert" ) func decodeB64(x string) ([]byte, error) { diff --git a/script.go b/types/script.go similarity index 99% rename from script.go rename to types/script.go index 3fbce2a..52dfabd 100644 --- a/script.go +++ b/types/script.go @@ -1,8 +1,9 @@ -package aptos +package types import ( - "github.com/aptos-labs/aptos-go-sdk/bcs" "math/big" + + "github.com/aptos-labs/aptos-go-sdk/bcs" ) //region Script diff --git a/signedTransaction.go b/types/signedTransaction.go similarity index 90% rename from signedTransaction.go rename to types/signedTransaction.go index d782557..f39753d 100644 --- a/signedTransaction.go +++ b/types/signedTransaction.go @@ -1,9 +1,11 @@ -package aptos +package types import ( "errors" + "github.com/aptos-labs/aptos-go-sdk/bcs" "github.com/aptos-labs/aptos-go-sdk/crypto" + "github.com/aptos-labs/aptos-go-sdk/util" ) // SignedTransactionVariant is the variant for a signed transaction @@ -52,7 +54,7 @@ var TransactionPrefix *[]byte // Note: At the moment, this assumes that the transaction is a UserTransaction func (txn *SignedTransaction) Hash() (string, error) { if TransactionPrefix == nil { - hash := Sha3256Hash([][]byte{[]byte("APTOS::Transaction")}) + hash := util.Sha3256Hash([][]byte{[]byte("APTOS::Transaction")}) TransactionPrefix = &hash } @@ -64,8 +66,8 @@ func (txn *SignedTransaction) Hash() (string, error) { // Transaction signature is defined as, the domain separated prefix based on struct (Transaction) // Then followed by the type of the transaction for the enum, UserTransaction is 0 // Then followed by BCS encoded bytes of the signed transaction - hashBytes := Sha3256Hash([][]byte{*TransactionPrefix, {byte(UserTransactionVariant)}, txnBytes}) - return BytesToHex(hashBytes), nil + hashBytes := util.Sha3256Hash([][]byte{*TransactionPrefix, {byte(UserTransactionVariant)}, txnBytes}) + return util.BytesToHex(hashBytes), nil } //region SignedTransaction bcs.Struct diff --git a/transactionAuthenticator.go b/types/transactionAuthenticator.go similarity index 99% rename from transactionAuthenticator.go rename to types/transactionAuthenticator.go index 22cc9d6..789040c 100644 --- a/transactionAuthenticator.go +++ b/types/transactionAuthenticator.go @@ -1,7 +1,8 @@ -package aptos +package types import ( "fmt" + "github.com/aptos-labs/aptos-go-sdk/bcs" "github.com/aptos-labs/aptos-go-sdk/crypto" ) diff --git a/transactionPayload.go b/types/transactionPayload.go similarity index 99% rename from transactionPayload.go rename to types/transactionPayload.go index 8b7e86a..53f68ec 100644 --- a/transactionPayload.go +++ b/types/transactionPayload.go @@ -1,8 +1,9 @@ -package aptos +package types import ( "errors" "fmt" + "github.com/aptos-labs/aptos-go-sdk/bcs" ) diff --git a/transactions_test.go b/types/transactions_test.go similarity index 99% rename from transactions_test.go rename to types/transactions_test.go index d3e8643..2a67bbc 100644 --- a/transactions_test.go +++ b/types/transactions_test.go @@ -1,9 +1,10 @@ -package aptos +package types import ( + "testing" + "github.com/aptos-labs/aptos-go-sdk/bcs" "github.com/stretchr/testify/assert" - "testing" ) func TestRawTransactionSign(t *testing.T) { diff --git a/typetag.go b/types/typetag.go similarity index 99% rename from typetag.go rename to types/typetag.go index 5e3b7cc..aa0e347 100644 --- a/typetag.go +++ b/types/typetag.go @@ -1,9 +1,10 @@ -package aptos +package types import ( "fmt" - "github.com/aptos-labs/aptos-go-sdk/bcs" "strings" + + "github.com/aptos-labs/aptos-go-sdk/bcs" ) //region TypeTag diff --git a/typetag_test.go b/types/typetag_test.go similarity index 99% rename from typetag_test.go rename to types/typetag_test.go index 05d6d3d..4891cee 100644 --- a/typetag_test.go +++ b/types/typetag_test.go @@ -1,9 +1,10 @@ -package aptos +package types import ( + "testing" + "github.com/aptos-labs/aptos-go-sdk/bcs" "github.com/stretchr/testify/assert" - "testing" ) func TestTypeTag(t *testing.T) { diff --git a/util.go b/util.go deleted file mode 100644 index bbad7ab..0000000 --- a/util.go +++ /dev/null @@ -1,35 +0,0 @@ -package aptos - -import ( - "math/big" - - "github.com/aptos-labs/aptos-go-sdk/util" -) - -// -- Note these are copied from internal/util/util.go to prevent package loops, but still allow devs to use it - -// ParseHex Convenience function to deal with 0x at the beginning of hex strings -func ParseHex(hexStr string) ([]byte, error) { - // This had to be redefined separately to get around a package loop - return util.ParseHex(hexStr) -} - -// Sha3256Hash takes a hash of the given sets of bytes -func Sha3256Hash(bytes [][]byte) (output []byte) { - return util.Sha3256Hash(bytes) -} - -// BytesToHex converts bytes to a 0x prefixed hex string -func BytesToHex(bytes []byte) string { - return util.BytesToHex(bytes) -} - -// StrToUint64 converts a string to a uint64 -func StrToUint64(s string) (uint64, error) { - return util.StrToUint64(s) -} - -// StrToBigInt converts a string to a big.Int -func StrToBigInt(val string) (num *big.Int, err error) { - return util.StrToBigInt(val) -} diff --git a/util_test.go b/util/util_test.go similarity index 86% rename from util_test.go rename to util/util_test.go index b4458f7..7d920dd 100644 --- a/util_test.go +++ b/util/util_test.go @@ -1,18 +1,11 @@ -package aptos +package util import ( - "github.com/stretchr/testify/assert" "math/big" "testing" -) - -var testConfig = LocalnetConfig -// createTestClient to use for testing for only one place to configure the network -// TODO: Allow overrides with environment variable? -func createTestClient() (*Client, error) { - return NewClient(testConfig) -} + "github.com/stretchr/testify/assert" +) func TestSHA3_256Hash(t *testing.T) { input := [][]byte{{0x1}, {0x2}, {0x3}} From 1bbd3f37726c548b50f90f85d7d28be214f8ba1c Mon Sep 17 00:00:00 2001 From: andrew Date: Sat, 27 Jul 2024 20:16:26 -0700 Subject: [PATCH 3/4] finish out rest of migration --- examples/external_signing/main_test.go | 4 +- examples/fungible_asset/main.go | 21 +++++---- examples/fungible_asset/main_test.go | 4 +- examples/onchain_multisig/main.go | 5 +- examples/onchain_multisig/main_test.go | 4 +- examples/performance_transaction/main.go | 19 ++++---- examples/performance_transaction/main_test.go | 4 +- .../sending_concurrent_transactions/main.go | 38 +++++++-------- .../main_test.go | 4 +- examples/sponsored_transaction/main.go | 46 ++++++++++--------- examples/sponsored_transaction/main_test.go | 4 +- 11 files changed, 88 insertions(+), 65 deletions(-) diff --git a/examples/external_signing/main_test.go b/examples/external_signing/main_test.go index 16f90be..148c1b3 100644 --- a/examples/external_signing/main_test.go +++ b/examples/external_signing/main_test.go @@ -2,9 +2,11 @@ package main import ( "testing" + + "github.com/aptos-labs/aptos-go-sdk/client" ) func Test_Main(t *testing.T) { t.Parallel() - example(types.LocalnetConfig) + example(client.LocalnetConfig) } diff --git a/examples/fungible_asset/main.go b/examples/fungible_asset/main.go index ca5e1d3..ecf5140 100644 --- a/examples/fungible_asset/main.go +++ b/examples/fungible_asset/main.go @@ -6,7 +6,10 @@ import ( "fmt" "github.com/aptos-labs/aptos-go-sdk/bcs" + "github.com/aptos-labs/aptos-go-sdk/client" "github.com/aptos-labs/aptos-go-sdk/crypto" + "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/aptos-labs/aptos-go-sdk/util" ) const testEd25519PrivateKey = "0xc5338cd251c22daa8c9c9cc94f498cc8a5c7e1d2e75287a5dda91096fe64efa5" @@ -34,23 +37,23 @@ func example(networkConfig client.NetworkConfig) { } // Fund the sender with the faucet to create it on-chain - err = client.Fund(sender.Address, 100_000_000) + err = aptosClient.Fund(sender.Address, 100_000_000) if err != nil { panic("Failed to fund sender:" + err.Error()) } // Publish the package for FA - metadataBytes, err := types.ParseHex(metadata) - bytecodeBytes, err := types.ParseHex(bytecode) + metadataBytes, err := util.ParseHex(metadata) + bytecodeBytes, err := util.ParseHex(bytecode) payload, err := types.PublishPackagePayloadFromJsonFile(metadataBytes, [][]byte{bytecodeBytes}) if err != nil { panic("Failed to create publish payload:" + err.Error()) } - response, err := client.BuildSignAndSubmitTransaction(sender, *payload) + response, err := aptosClient.BuildSignAndSubmitTransaction(sender, *payload) if err != nil { panic("Failed to build sign and submit publish transaction:" + err.Error()) } - waitResponse, err := client.WaitForTransaction(response.Hash) + waitResponse, err := aptosClient.WaitForTransaction(response.Hash) if err != nil { panic("Failed to wait for publish transaction:" + err.Error()) } @@ -62,7 +65,7 @@ func example(networkConfig client.NetworkConfig) { // Get the fungible asset address by view function rupeeModule := types.ModuleId{Address: sender.Address, Name: "rupee"} var noTypeTags []types.TypeTag - viewResponse, err := aptosClient.View(&types.ViewPayload{ + viewResponse, err := aptosClient.View(&client.ViewPayload{ Module: rupeeModule, Function: "fa_address", ArgTypes: noTypeTags, @@ -76,7 +79,7 @@ func example(networkConfig client.NetworkConfig) { if err != nil { panic("Failed to parse fa address:" + err.Error()) } - faClient, err := client.NewFungibleAssetClient(client, faMetadataAddress) + faClient, err := client.NewFungibleAssetClient(aptosClient, faMetadataAddress) if err != nil { panic("Failed to create fungible asset client:" + err.Error()) } @@ -92,7 +95,7 @@ func example(networkConfig client.NetworkConfig) { panic("Failed to serialize amount:" + err.Error()) } serializedSenderAddress, _ := bcs.Serialize(&sender.Address) // This can't fail - response, err = client.BuildSignAndSubmitTransaction(sender, types.TransactionPayload{ + response, err = aptosClient.BuildSignAndSubmitTransaction(sender, types.TransactionPayload{ Payload: &types.EntryFunction{ Module: rupeeModule, Function: "mint", @@ -104,7 +107,7 @@ func example(networkConfig client.NetworkConfig) { panic("Failed to build sign and submit mint transaction:" + err.Error()) } fmt.Printf("Submitted mint as: %s\n", response.Hash) - _, err = client.WaitForTransaction(response.Hash) + _, err = aptosClient.WaitForTransaction(response.Hash) if err != nil { panic("Failed to wait for publish transaction:" + err.Error()) } diff --git a/examples/fungible_asset/main_test.go b/examples/fungible_asset/main_test.go index 16f90be..148c1b3 100644 --- a/examples/fungible_asset/main_test.go +++ b/examples/fungible_asset/main_test.go @@ -2,9 +2,11 @@ package main import ( "testing" + + "github.com/aptos-labs/aptos-go-sdk/client" ) func Test_Main(t *testing.T) { t.Parallel() - example(types.LocalnetConfig) + example(client.LocalnetConfig) } diff --git a/examples/onchain_multisig/main.go b/examples/onchain_multisig/main.go index 7054e9c..7ee6647 100644 --- a/examples/onchain_multisig/main.go +++ b/examples/onchain_multisig/main.go @@ -10,6 +10,7 @@ import ( "github.com/aptos-labs/aptos-go-sdk/bcs" "github.com/aptos-labs/aptos-go-sdk/client" "github.com/aptos-labs/aptos-go-sdk/types" + "github.com/aptos-labs/aptos-go-sdk/util" ) const TransferAmount = uint64(1_000_000) @@ -204,7 +205,7 @@ func multisigResource(client *client.Client, multisigAddress *types.AccountAddre numSigsRequiredStr := resourceData["num_signatures_required"].(string) - numSigsRequired, err := types.StrToUint64(numSigsRequiredStr) + numSigsRequired, err := util.StrToUint64(numSigsRequiredStr) if err != nil { panic("Failed to convert string to u64: " + err.Error()) } @@ -329,5 +330,5 @@ func submitAndWait(client *client.Client, sender *types.Account, payload types.T } func main() { - example(types.DevnetConfig) + example(client.DevnetConfig) } diff --git a/examples/onchain_multisig/main_test.go b/examples/onchain_multisig/main_test.go index 16f90be..148c1b3 100644 --- a/examples/onchain_multisig/main_test.go +++ b/examples/onchain_multisig/main_test.go @@ -2,9 +2,11 @@ package main import ( "testing" + + "github.com/aptos-labs/aptos-go-sdk/client" ) func Test_Main(t *testing.T) { t.Parallel() - example(types.LocalnetConfig) + example(client.LocalnetConfig) } diff --git a/examples/performance_transaction/main.go b/examples/performance_transaction/main.go index 56f104f..79ba62d 100644 --- a/examples/performance_transaction/main.go +++ b/examples/performance_transaction/main.go @@ -4,16 +4,19 @@ package main import ( "encoding/json" "time" + + "github.com/aptos-labs/aptos-go-sdk/client" + "github.com/aptos-labs/aptos-go-sdk/types" ) // example This example shows you how to improve performance of the transaction submission // // Speed can be improved by locally handling the sequence number, gas price, and other factors -func example(networkConfig types.NetworkConfig) { +func example(networkConfig client.NetworkConfig) { start := time.Now() before := time.Now() // Create a client for Aptos - client, err := types.NewClient(networkConfig) + aptosClient, err := client.NewClient(networkConfig) if err != nil { panic("Failed to create client:" + err.Error()) } @@ -30,7 +33,7 @@ func example(networkConfig types.NetworkConfig) { before = time.Now() // Fund the sender with the faucet to create it on-chain - err = client.Fund(sender.Address, 100_000_000) + err = aptosClient.Fund(sender.Address, 100_000_000) println("Fund sender:", time.Since(before).Milliseconds(), "ms") @@ -50,8 +53,8 @@ func example(networkConfig types.NetworkConfig) { panic("Failed to serialize arguments:" + err.Error()) } - rawTxn, err := client.BuildTransaction(sender.Address, - types.TransactionPayload{Payload: payload}, types.SequenceNumber(0)) // Use the sequence number to skip fetching it + rawTxn, err := aptosClient.BuildTransaction(sender.Address, + types.TransactionPayload{Payload: payload}, client.SequenceNumber(0)) // Use the sequence number to skip fetching it if err != nil { panic("Failed to build transaction:" + err.Error()) } @@ -69,7 +72,7 @@ func example(networkConfig types.NetworkConfig) { println("Sign transaction:", time.Since(before).Milliseconds(), "ms") before = time.Now() - submitResult, err := client.SubmitTransaction(signedTxn) + submitResult, err := aptosClient.SubmitTransaction(signedTxn) if err != nil { panic("Failed to submit transaction:" + err.Error()) } @@ -78,7 +81,7 @@ func example(networkConfig types.NetworkConfig) { // Wait for the transaction before = time.Now() - txn, err := client.WaitForTransaction(txnHash) + txn, err := aptosClient.WaitForTransaction(txnHash) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } @@ -90,5 +93,5 @@ func example(networkConfig types.NetworkConfig) { } func main() { - example(types.DevnetConfig) + example(client.DevnetConfig) } diff --git a/examples/performance_transaction/main_test.go b/examples/performance_transaction/main_test.go index 16f90be..148c1b3 100644 --- a/examples/performance_transaction/main_test.go +++ b/examples/performance_transaction/main_test.go @@ -2,9 +2,11 @@ package main import ( "testing" + + "github.com/aptos-labs/aptos-go-sdk/client" ) func Test_Main(t *testing.T) { t.Parallel() - example(types.LocalnetConfig) + example(client.LocalnetConfig) } diff --git a/examples/sending_concurrent_transactions/main.go b/examples/sending_concurrent_transactions/main.go index 512074d..028c781 100644 --- a/examples/sending_concurrent_transactions/main.go +++ b/examples/sending_concurrent_transactions/main.go @@ -5,10 +5,12 @@ import ( "time" "github.com/aptos-labs/aptos-go-sdk/api" + "github.com/aptos-labs/aptos-go-sdk/client" + "github.com/aptos-labs/aptos-go-sdk/types" ) -func setup(networkConfig types.NetworkConfig) (*types.Client, types.TransactionSigner) { - client, err := types.NewClient(networkConfig) +func setup(networkConfig client.NetworkConfig) (*client.Client, types.TransactionSigner) { + aptosClient, err := client.NewClient(networkConfig) if err != nil { panic("Failed to create client:" + err.Error()) } @@ -18,12 +20,12 @@ func setup(networkConfig types.NetworkConfig) (*types.Client, types.TransactionS panic("Failed to create sender:" + err.Error()) } - err = client.Fund(sender.Address, 100_000_000) + err = aptosClient.Fund(sender.Address, 100_000_000) if err != nil { panic("Failed to fund sender:" + err.Error()) } - return client, sender + return aptosClient, sender } func payload() types.TransactionPayload { @@ -40,8 +42,8 @@ func payload() types.TransactionPayload { return types.TransactionPayload{Payload: p} } -func sendManyTransactionsSerially(networkConfig types.NetworkConfig, numTransactions uint64) { - client, sender := setup(networkConfig) +func sendManyTransactionsSerially(networkConfig client.NetworkConfig, numTransactions uint64) { + aptosClient, sender := setup(networkConfig) responses := make([]*api.SubmitTransactionResponse, numTransactions) payload := payload() @@ -49,7 +51,7 @@ func sendManyTransactionsSerially(networkConfig types.NetworkConfig, numTransact senderAddress := sender.AccountAddress() sequenceNumber := uint64(0) for i := uint64(0); i < numTransactions; i++ { - rawTxn, err := client.BuildTransaction(senderAddress, payload, types.SequenceNumber(sequenceNumber)) + rawTxn, err := aptosClient.BuildTransaction(senderAddress, payload, client.SequenceNumber(sequenceNumber)) if err != nil { panic("Failed to build transaction:" + err.Error()) } @@ -59,7 +61,7 @@ func sendManyTransactionsSerially(networkConfig types.NetworkConfig, numTransact panic("Failed to sign transaction:" + err.Error()) } - submitResult, err := client.SubmitTransaction(signedTxn) + submitResult, err := aptosClient.SubmitTransaction(signedTxn) if err != nil { panic("Failed to submit transaction:" + err.Error()) } @@ -68,7 +70,7 @@ func sendManyTransactionsSerially(networkConfig types.NetworkConfig, numTransact } // Wait on last transaction - response, err := client.WaitForTransaction(responses[numTransactions-1].Hash) + response, err := aptosClient.WaitForTransaction(responses[numTransactions-1].Hash) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } @@ -77,21 +79,21 @@ func sendManyTransactionsSerially(networkConfig types.NetworkConfig, numTransact } } -func sendManyTransactionsConcurrently(networkConfig types.NetworkConfig, numTransactions uint64) { - client, sender := setup(networkConfig) +func sendManyTransactionsConcurrently(networkConfig client.NetworkConfig, numTransactions uint64) { + aptosClient, sender := setup(networkConfig) payload := payload() // start submission goroutine - payloads := make(chan types.TransactionBuildPayload, 50) - results := make(chan types.TransactionSubmissionResponse, 50) - go client.BuildSignAndSubmitTransactions(sender, payloads, results) + payloads := make(chan client.TransactionBuildPayload, 50) + results := make(chan client.TransactionSubmissionResponse, 50) + go aptosClient.BuildSignAndSubmitTransactions(sender, payloads, results) // Submit transactions to goroutine go func() { for i := uint64(0); i < numTransactions; i++ { - payloads <- types.TransactionBuildPayload{ + payloads <- client.TransactionBuildPayload{ Id: i, - Type: types.TransactionSubmissionTypeSingle, + Type: client.TransactionSubmissionTypeSingle, Inner: payload, } } @@ -109,7 +111,7 @@ func sendManyTransactionsConcurrently(networkConfig types.NetworkConfig, numTran // example This example shows you how to improve performance of the transaction submission // // Speed can be improved by locally handling the sequence number, gas price, and other factors -func example(networkConfig types.NetworkConfig, numTransactions uint64) { +func example(networkConfig client.NetworkConfig, numTransactions uint64) { println("Sending", numTransactions, "transactions Serially") startSerial := time.Now() sendManyTransactionsSerially(networkConfig, numTransactions) @@ -126,5 +128,5 @@ func example(networkConfig types.NetworkConfig, numTransactions uint64) { } func main() { - example(types.DevnetConfig, 100) + example(client.DevnetConfig, 100) } diff --git a/examples/sending_concurrent_transactions/main_test.go b/examples/sending_concurrent_transactions/main_test.go index 6cbc550..974549e 100644 --- a/examples/sending_concurrent_transactions/main_test.go +++ b/examples/sending_concurrent_transactions/main_test.go @@ -2,9 +2,11 @@ package main import ( "testing" + + "github.com/aptos-labs/aptos-go-sdk/client" ) func Test_Main(t *testing.T) { t.Parallel() - example(types.LocalnetConfig, 100) + example(client.LocalnetConfig, 100) } diff --git a/examples/sponsored_transaction/main.go b/examples/sponsored_transaction/main.go index 2f0ff5e..282d02f 100644 --- a/examples/sponsored_transaction/main.go +++ b/examples/sponsored_transaction/main.go @@ -4,16 +4,18 @@ package main import ( "fmt" + "github.com/aptos-labs/aptos-go-sdk/client" "github.com/aptos-labs/aptos-go-sdk/crypto" + "github.com/aptos-labs/aptos-go-sdk/types" ) const FundAmount = 100_000_000 const TransferAmount = 1_000 // example This example shows you how to make an APT transfer transaction in the simplest possible way -func example(networkConfig types.NetworkConfig) { +func example(networkConfig client.NetworkConfig) { // Create a client for Aptos - client, err := types.NewClient(networkConfig) + aptosClient, err := client.NewClient(networkConfig) if err != nil { panic("Failed to create client:" + err.Error()) } @@ -38,26 +40,26 @@ func example(networkConfig types.NetworkConfig) { fmt.Printf("Sponsor:%s\n", sponsor.Address.String()) // Fund the alice with the faucet to create it on-chain - err = client.Fund(alice.Address, FundAmount) + err = aptosClient.Fund(alice.Address, FundAmount) if err != nil { panic("Failed to fund alice:" + err.Error()) } // And the sponsor - err = client.Fund(sponsor.Address, FundAmount) + err = aptosClient.Fund(sponsor.Address, FundAmount) if err != nil { panic("Failed to fund sponsor:" + err.Error()) } - aliceBalance, err := client.AccountAPTBalance(alice.Address) + aliceBalance, err := aptosClient.AccountAPTBalance(alice.Address) if err != nil { panic("Failed to retrieve alice balance:" + err.Error()) } - bobBalance, err := client.AccountAPTBalance(bob.Address) + bobBalance, err := aptosClient.AccountAPTBalance(bob.Address) if err != nil { panic("Failed to retrieve bob balance:" + err.Error()) } - sponsorBalance, err := client.AccountAPTBalance(sponsor.Address) + sponsorBalance, err := aptosClient.AccountAPTBalance(sponsor.Address) if err != nil { panic("Failed to retrieve sponsor balance:" + err.Error()) } @@ -71,12 +73,12 @@ func example(networkConfig types.NetworkConfig) { if err != nil { panic("Failed to build transfer payload:" + err.Error()) } - rawTxn, err := client.BuildTransactionMultiAgent( + rawTxn, err := aptosClient.BuildTransactionMultiAgent( alice.Address, types.TransactionPayload{ Payload: transferPayload, }, - types.FeePayer(&sponsor.Address), + client.FeePayer(&sponsor.Address), ) if err != nil { panic("Failed to build transaction:" + err.Error()) @@ -102,7 +104,7 @@ func example(networkConfig types.NetworkConfig) { } // Submit and wait for it to complete - submitResult, err := client.SubmitTransaction(signedFeePayerTxn) + submitResult, err := aptosClient.SubmitTransaction(signedFeePayerTxn) if err != nil { panic("Failed to submit transaction:" + err.Error()) } @@ -110,19 +112,19 @@ func example(networkConfig types.NetworkConfig) { println("Submitted transaction hash:", txnHash) // Wait for the transaction - _, err = client.WaitForTransaction(txnHash) + _, err = aptosClient.WaitForTransaction(txnHash) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } - aliceBalance, err = client.AccountAPTBalance(alice.Address) + aliceBalance, err = aptosClient.AccountAPTBalance(alice.Address) if err != nil { panic("Failed to retrieve alice balance:" + err.Error()) } - bobBalance, err = client.AccountAPTBalance(bob.Address) + bobBalance, err = aptosClient.AccountAPTBalance(bob.Address) if err != nil { panic("Failed to retrieve bob balance:" + err.Error()) } - sponsorBalance, err = client.AccountAPTBalance(sponsor.Address) + sponsorBalance, err = aptosClient.AccountAPTBalance(sponsor.Address) if err != nil { panic("Failed to retrieve sponsor balance:" + err.Error()) } @@ -133,12 +135,12 @@ func example(networkConfig types.NetworkConfig) { fmt.Printf("\n=== Now do it without knowing the signer ahead of time ===\n") - rawTxn, err = client.BuildTransactionMultiAgent( + rawTxn, err = aptosClient.BuildTransactionMultiAgent( alice.Address, types.TransactionPayload{ Payload: transferPayload, }, - types.FeePayer(&types.AccountZero), // Note that the Address is 0x0, because we don't know the signer + client.FeePayer(&types.AccountZero), // Note that the Address is 0x0, because we don't know the signer ) if err != nil { panic("Failed to build transaction:" + err.Error()) @@ -172,7 +174,7 @@ func example(networkConfig types.NetworkConfig) { } // Submit and wait for it to complete - submitResult, err = client.SubmitTransaction(signedFeePayerTxn) + submitResult, err = aptosClient.SubmitTransaction(signedFeePayerTxn) if err != nil { panic("Failed to submit transaction:" + err.Error()) } @@ -180,19 +182,19 @@ func example(networkConfig types.NetworkConfig) { println("Submitted transaction hash:", txnHash) // Wait for the transaction - _, err = client.WaitForTransaction(txnHash) + _, err = aptosClient.WaitForTransaction(txnHash) if err != nil { panic("Failed to wait for transaction:" + err.Error()) } - aliceBalance, err = client.AccountAPTBalance(alice.Address) + aliceBalance, err = aptosClient.AccountAPTBalance(alice.Address) if err != nil { panic("Failed to retrieve alice balance:" + err.Error()) } - bobBalance, err = client.AccountAPTBalance(bob.Address) + bobBalance, err = aptosClient.AccountAPTBalance(bob.Address) if err != nil { panic("Failed to retrieve bob balance:" + err.Error()) } - sponsorBalance, err = client.AccountAPTBalance(sponsor.Address) + sponsorBalance, err = aptosClient.AccountAPTBalance(sponsor.Address) if err != nil { panic("Failed to retrieve sponsor balance:" + err.Error()) } @@ -203,5 +205,5 @@ func example(networkConfig types.NetworkConfig) { } func main() { - example(types.DevnetConfig) + example(client.DevnetConfig) } diff --git a/examples/sponsored_transaction/main_test.go b/examples/sponsored_transaction/main_test.go index 16f90be..148c1b3 100644 --- a/examples/sponsored_transaction/main_test.go +++ b/examples/sponsored_transaction/main_test.go @@ -2,9 +2,11 @@ package main import ( "testing" + + "github.com/aptos-labs/aptos-go-sdk/client" ) func Test_Main(t *testing.T) { t.Parallel() - example(types.LocalnetConfig) + example(client.LocalnetConfig) } From 00d85d164fff622398051829020d1c9e8517009a Mon Sep 17 00:00:00 2001 From: andrew Date: Sat, 27 Jul 2024 20:16:54 -0700 Subject: [PATCH 4/4] check tests can build via scripts --- scripts/build-test.sh | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100755 scripts/build-test.sh diff --git a/scripts/build-test.sh b/scripts/build-test.sh new file mode 100755 index 0000000..2787c3c --- /dev/null +++ b/scripts/build-test.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +# Change to the root of the git repository +cd "$(git rev-parse --show-toplevel)" + +go test -c ./... \ No newline at end of file