Git Product home page Git Product logo

go-aptos-sdk's Introduction

Aptos Goland SDK

Documentation (master) License

The Aptos Golang SDK for ComingChat. We welcome other developers to participate in the development and testing of golang-sdk @aptos-labs!

Install

go get github.com/coming-chat/go-aptos

Usage

Account

import "github.com/coming-chat/go-aptos/aptosaccount"

// Import account with mnemonic
account, err := aptosaccount.NewAccountWithMnemonic(mnemonic)

// Import account with private key
privateKey, err := hex.DecodeString("4ec5a9eefc0bb86027a6f3ba718793c813505acc25ed09447caf6a069accdd4b")
account, err := aptosaccount.NewAccount(privateKey)

// Get private key, public key, address
fmt.Printf("privateKey = %x\n", account.PrivateKey[:32])
fmt.Printf(" publicKey = %x\n", account.PublicKey)
fmt.Printf("   address = %x\n", account.AuthKey)

// Sign data
signedData := account.Sign(data, "")

Transfer Aptos Coin (BCS)

NOTE: The implementation of bcs is based on the lcs library

import "github.com/coming-chat/go-aptos/aptosaccount"
import "github.com/coming-chat/go-aptos/aptosclient"
import "github.com/coming-chat/go-aptos/aptostypes"
import txBuilder "github.com/coming-chat/go-aptos/transaction_builder"

account, err := NewAccountWithMnemonic(mnemonic)
fromAddress := "0x" + hex.EncodeToString(account.AuthKey[:])

toAddress := "0xcdbe33da8d218e97a9bec6443ba4a1b1858494f29142976d357f4770c384e015"
amount := uint64(100)

// Initialize the client
restUrl := "https://fullnode.devnet.aptoslabs.com"
client, err := aptosclient.Dial(context.Background(), restUrl)

// Get Sender's account data and ledger info
accountData, err := client.GetAccount(fromAddress)
ledgerInfo, err := client.LedgerInfo()

// Get gas price
gasPrice, err := client.EstimateGasPrice()

// Build paylod
moduleName, err := txBuilder.NewModuleIdFromString("0x1::account")
toAddr, err := txBuilder.NewAccountAddressFromHex(toAddress)
toAmountBytes := txBuilder.BCSSerializeBasicValue(amount)

payload := txBuilder.TransactionPayloadEntryFunction{
	ModuleName:   *moduleName,
	FunctionName: "transfer",
	TyArgs:       []txBuilder.TypeTag{},
	Args: [][]byte{
		toAddr[:], toAmountBytes,
	},
}

// Build transaction
txn = &txBuilder.RawTransaction{
	Sender:                  from.AuthKey,
	SequenceNumber:          data.SequenceNumber,
	Payload:                 payload,
	MaxGasAmount:            2000,
	GasUnitPrice:            gasPrice,
	ExpirationTimestampSecs: info.LedgerTimestamp + 600,
	ChainId:                 uint8(info.ChainId),
}

// Sign raw transaction with account, and encode into data using BCS
signedTxn, err := txBuilder.GenerateBCSTransaction(account, txn)

// Submit transaction with BCS format.
newTxn, err := client.SubmitSignedBCSTransaction(signedTxn)
fmt.Printf("tx hash = %v\n", newTx.Hash)

Transfer Aptos Coin (JSON)

import "github.com/coming-chat/go-aptos/aptosaccount"
import "github.com/coming-chat/go-aptos/aptosclient"
import "github.com/coming-chat/go-aptos/aptostypes"

account, err := NewAccountWithMnemonic(mnemonic)
fromAddress := "0x" + hex.EncodeToString(account.AuthKey[:])

toAddress := "0xcdbe33da8d218e97a9bec6443ba4a1b1858494f29142976d357f4770c384e015"
amount := "100"

// Initialize the client
restUrl := "https://fullnode.devnet.aptoslabs.com"
client, err := aptosclient.Dial(context.Background(), restUrl)

// Get Sender's account data and ledger info
accountData, err := client.GetAccount(fromAddress)
ledgerInfo, err := client.LedgerInfo()

// Get gas price
gasPrice, err := client.EstimateGasPrice()

// Build paylod
payload := &aptostypes.Payload{
	Type: 		   "entry_function_payload",
	Function:      "0x1::coin::transfer",
	TypeArguments: []string{"0x1::aptos_coin::AptosCoin"},
	Arguments: []interface{}{
		toAddress, amount,
	},
}

// Build transaction
transaction := &aptostypes.Transaction{
	Sender:                  fromAddress,
	SequenceNumber:          accountData.SequenceNumber,
	MaxGasAmount:            2000,
	GasUnitPrice:            gasPrice,
	Payload:                 payload,
	ExpirationTimestampSecs: ledgerInfo.LedgerTimestamp + 600, // 10 minutes timeout
}

// Get signing message from remote server
// Note: Later we will implement the local use of BCS encoding to create signing messages
signingMessage, err := client.CreateTransactionSigningMessage(transaction)

// Sign message and complete transaction information
signatureData := account.Sign(signingMessage, "")
signatureHex := "0x" + hex.EncodeToString(signatureData)
publicKey := "0x" + hex.EncodeToString(account.PublicKey)
transaction.Signature = &aptostypes.Signature{
	Type:      "ed25519_signature",
	PublicKey: publicKey,
	Signature: signatureHex,
}

// Submit transaction
newTx, err := client.SubmitTransaction(transaction)
fmt.Printf("tx hash = %v\n", newTx.Hash)

TODO

  • Locally implement BCS encoding of coin transfer transaction data
  • Support Move action BCS
  • Support Multi sign

go-aptos-sdk's People

Contributors

gguoss avatar gkirito avatar iosguang avatar xiang-xx avatar zhangguiguang avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.