supra-ts-sdk - v2.0.0
    Preparing search index...

    Class Build

    The Build class provides methods for building raw transactions.

    Index
    • The constructor function takes a NetworkConfig object as a parameter and assigns it to the networkInformation property.

      Parameters

      • networkInformation: NetworkConfig

        A NetworkConfig object that contains information about the network on which the Supra client is running.

      Returns Build

      import { SupraClient,Network } from "supra-ts-sdk";

      const supra = new SupraClient({ network: Network.TESTNET });
    • Create raw transaction object for simple type txn Don't need to serialize arguments as they serialize on the fly using function abi. When neither the call nor the client sets maxGas, the max gas is DEFAULT_MAX_GAS_UNITS, at most the number of gas units that the sender's SUPRA balance pays for at the gas unit price (one balance read; none with estimateMaxGas: false). See OptionalTransactionPayloadArgs.

      Parameters

      Returns Promise<ExtendedRawTransaction>

      Raw transaction object

      RangeError when the call sets no txExpiryTime and SupraConfig.txExpirySecs is more than the node's maximum time to live, and the error of a failed read of that maximum (getTransactionParameters()); the maximum is read once per client and there is no fallback

      import { Network, SupraAccount, SupraClient } from "supra-ts-sdk";

      const supra = new SupraClient({ network: Network.TESTNET });
      const account = new SupraAccount(); // an account that holds SUPRA

      async function runExample() {

      const supraCoinTransferRawTransaction = await supra.transaction.build.simple({
      senderAddress: account.address(),
      senderSequenceNumber: (await supra.account.getAccountInfo({ accountAddress: account.address() })).sequence_number,
      function: "0x1::supra_account::transfer",
      functionTypeArgs: [],
      functionArgs: ["0x2", 10000n]
      });

      console.log(supraCoinTransferRawTransaction);
      }

      runExample().catch(console.error);
    • Create raw transaction object for entry_function_payload type txn

      Parameters

      • args: {
            senderAddress: AccountAddressInput;
            senderSequenceNumber: bigint;
            function: `${string}::${string}::${string}`;
            functionTypeArgs: TypeTag[];
            functionArgs: Uint8Array<ArrayBufferLike>[];
            optionalTransactionPayloadArgs?: OptionalTransactionPayloadArgs;
        }
        • senderAddress: AccountAddressInput

          Sender account address

        • senderSequenceNumber: bigint

          Sender account sequence number

        • function: `${string}::${string}::${string}`

          Target function name as MoveFunctionId

        • functionTypeArgs: TypeTag[]

          Target function type args

        • functionArgs: Uint8Array<ArrayBufferLike>[]

          Target function args

        • OptionaloptionalTransactionPayloadArgs?: OptionalTransactionPayloadArgs

          Optional arguments for transaction payload. This builder makes no request: without a maxGas on the call or the client, the max gas is DEFAULT_MAX_GAS_UNITS (20,000 units). The node requires the sender's SUPRA balance to cover max gas × gas unit price at validation: 20,000 units at a price of 100,000 quants need 20 SUPRA (2,000,000,000 quants). A sender with less must set maxGas. The builder cannot read the node's gas unit price estimate: without a gasUnitPrice on the call or the client it throws a RangeError; supra.getEstimatedGasUnitPrice() returns the estimate.

      Returns ExtendedRawTransaction

      Raw transaction object

      import { BCS, Network, SupraAccount, SupraClient } from "supra-ts-sdk";

      const supra = new SupraClient({ network: Network.TESTNET });
      const account = new SupraAccount(); // an account that holds SUPRA
      const receiverAddress = new SupraAccount().address();

      async function runExample() {

      const supraCoinTransferRawTransaction = supra.transaction.build.rawTxnObject({
      senderAddress: account.address(),
      senderSequenceNumber: (await supra.account.getAccountInfo({ accountAddress: account.address() })).sequence_number,
      function: "0x1::supra_account::transfer",
      functionTypeArgs: [],
      functionArgs: [receiverAddress.toUint8Array(), BCS.bcsSerializeUint64(10000n)],
      optionalTransactionPayloadArgs: { gasUnitPrice: await supra.getEstimatedGasUnitPrice() },
      });

      console.log(supraCoinTransferRawTransaction);
      }

      runExample().catch(console.error);
    • Create raw transaction for script_payload type txn

      Parameters

      • args: {
            senderAddress: AccountAddressInput;
            senderSequenceNumber: bigint;
            scriptCode: Uint8Array;
            scriptTypeArgs: TypeTag[];
            scriptArgs: TransactionArgument[];
            optionalTransactionPayloadArgs?: OptionalTransactionPayloadArgs;
        }
        • senderAddress: AccountAddressInput

          Sender account address

        • senderSequenceNumber: bigint

          Sender account sequence number

        • scriptCode: Uint8Array

          Move script bytecode

        • scriptTypeArgs: TypeTag[]

          Type arguments that move script bytecode requires

        • scriptArgs: TransactionArgument[]

          Arguments to the move script bytecode function

        • OptionaloptionalTransactionPayloadArgs?: OptionalTransactionPayloadArgs

          Optional arguments for transaction payload. This builder makes no request: without a maxGas on the call or the client, the max gas is DEFAULT_MAX_GAS_UNITS (20,000 units). The node requires the sender's SUPRA balance to cover max gas × gas unit price at validation: 20,000 units at a price of 100,000 quants need 20 SUPRA (2,000,000,000 quants). A sender with less must set maxGas. The builder cannot read the node's gas unit price estimate: without a gasUnitPrice on the call or the client it throws a RangeError; supra.getEstimatedGasUnitPrice() returns the estimate.

      Returns ExtendedRawTransaction

      Raw script transaction object

      import { HexString, Network, SupraAccount, SupraClient, TxnBuilderTypes } from "supra-ts-sdk";

      const supra = new SupraClient({ network: Network.TESTNET });
      const account = new SupraAccount(); // an account that holds SUPRA

      async function runExample() {

      const moveScriptCodeHex = "0xa11ceb0b06000000050100040..."; // the compiled script

      const supraCoinTransferSerializedScriptRawTransaction = supra.transaction.build.scriptRawTxnObject({
      senderAddress: account.address(),
      senderSequenceNumber: (await supra.account.getAccountInfo({ accountAddress: account.address() })).sequence_number,
      scriptCode: new HexString(moveScriptCodeHex).toUint8Array(),
      scriptTypeArgs: [],
      scriptArgs: [new TxnBuilderTypes.TransactionArgumentU64(BigInt(1000))],
      optionalTransactionPayloadArgs: { gasUnitPrice: await supra.getEstimatedGasUnitPrice() }
      }).toBytes();

      console.log(supraCoinTransferSerializedScriptRawTransaction);
      }

      runExample().catch(console.error);
    • Create raw transaction object for automation_registration_payload type txn

      The registration parameters are version 2 when automationTaskType or automationPriority is given, and version 1 otherwise. Nodes of the v11.7.0 and v12 lines accept both versions. A version 1 registration and a version 2 registration of task type User without a priority register the same task; the node records the version in the transaction's payload.

      A priority belongs to system tasks only. The registry aborts the registration of a user task that carries one (EUSER_TASK_PRIORITY_NOT_SUPPORTED), so the builder throws a RangeError when automationPriority is given with task type "User" or with no task type.

      The node registers the task with 0x1::automation_registry, which emits an 0x1::automation_registry::AutomationTaskMetaData event whose task_index is the index that Automation.cancelAutomationTask and Automation.stopAutomationTasks take.

      Parameters

      • args: {
            senderAddress: AccountAddressInput;
            senderSequenceNumber: bigint;
            function: `${string}::${string}::${string}`;
            functionTypeArgs: TypeTag[];
            functionArgs: Uint8Array<ArrayBufferLike>[];
            automationMaxGasAmount: bigint;
            automationGasPriceCap: bigint;
            automationFeeCapForEpoch: bigint;
            automationExpirationTimestampSecs: bigint;
            automationAuxData: Uint8Array<ArrayBufferLike>[];
            automationTaskType?: AutomationTaskType;
            automationPriority?: bigint;
            optionalTransactionPayloadArgs?: OptionalTransactionPayloadArgs;
        }
        • senderAddress: AccountAddressInput

          Sender account address

        • senderSequenceNumber: bigint

          Sender account sequence number

        • function: `${string}::${string}::${string}`

          Target function name as MoveFunctionId

        • functionTypeArgs: TypeTag[]

          Target function type args

        • functionArgs: Uint8Array<ArrayBufferLike>[]

          Target function args

        • automationMaxGasAmount: bigint

          Max gas amount for automated transaction

        • automationGasPriceCap: bigint

          Gas unit price upper limit that user is willing to pay. It must be at least the node's minimum gas unit price (getMinGasUnitPrice()). Otherwise the node refuses the registration at validation: the submit call answers with a SupraAPIError (status 400, MoveTransactionValidationFailed with AUTOMATION_TASK_GAS_PRICE_CAP_BELOW_MIN_BOUND) and a simulation reports Invalid with the same status, as a SupraSimulationFailedError. The builder does not check the cap.

        • automationFeeCapForEpoch: bigint

          Maximum automation fee that user is willing to pay for epoch.

        • automationExpirationTimestampSecs: bigint

          Expiration time of the automated transaction in seconds since UTC Epoch start.

        • automationAuxData: Uint8Array<ArrayBufferLike>[]

          Reserved for future extensions of registration parameters. Where the node adds the task type and the priority to the auxiliary data (feature SUPRA_AUTOMATION_V2, enabled on Mainnet, Testnet and Devnet), the registry accepts only an empty list.

        • OptionalautomationTaskType?: AutomationTaskType

          Task type of a version 2 registration: "User" or "System". Only an account that the Supra framework has authorised to register system tasks can register a "System" task; the registration of any other account aborts.

        • OptionalautomationPriority?: bigint

          Priority of a system task, a u64; allowed only with automationTaskType: "System". A user task has no priority: the registry uses the task's index as its priority.

        • OptionaloptionalTransactionPayloadArgs?: OptionalTransactionPayloadArgs

          Optional arguments for transaction payload. This builder makes no request: without a maxGas on the call or the client, the max gas is DEFAULT_MAX_GAS_UNITS (20,000 units). The node requires the sender's SUPRA balance to cover max gas × gas unit price at validation: 20,000 units at a price of 100,000 quants need 20 SUPRA (2,000,000,000 quants). A sender with less must set maxGas. The builder cannot read the node's gas unit price estimate: without a gasUnitPrice on the call or the client it throws a RangeError; supra.getEstimatedGasUnitPrice() returns the estimate.

      Returns ExtendedRawTransaction

      Raw transaction object

      RangeError before building when automationTaskType is not "User" or "System", automationPriority is given without automationTaskType: "System", or automationPriority is not a bigint from 0 to 2^64 - 1

      import { BCS, MILLISECONDS_PER_SECOND, Network, SupraAccount, SupraClient } from "supra-ts-sdk";

      const supra = new SupraClient({ network: Network.TESTNET });
      const account = new SupraAccount(); // an account that holds SUPRA
      const receiverAddress = new SupraAccount().address();

      async function runExample() {
      const gasUnitPrice = await supra.getEstimatedGasUnitPrice();

      // Version 2 registration of a user task (a user task has no priority)
      const registration = supra.transaction.build.automationRegistrationRawTxnObject({
      senderAddress: account.address(),
      senderSequenceNumber: (await supra.account.getAccountInfo({ accountAddress: account.address() })).sequence_number,
      function: "0x1::supra_account::transfer",
      functionTypeArgs: [],
      functionArgs: [receiverAddress.toUint8Array(), BCS.bcsSerializeUint64(1000n)],
      automationMaxGasAmount: 500n,
      automationGasPriceCap: 2n * gasUnitPrice,
      automationFeeCapForEpoch: 1_000_000_000n,
      automationExpirationTimestampSecs: BigInt(Math.floor(Date.now() / MILLISECONDS_PER_SECOND) + 60 * 60),
      automationAuxData: [],
      automationTaskType: "User",
      optionalTransactionPayloadArgs: { gasUnitPrice },
      });

      const response = await registration.submitTransaction({
      senderAccount: account,
      enableTransactionWaitAndSimulationArgs: { enableWaitForTransaction: true },
      });
      console.log(response.hash, response.status);
      }

      runExample().catch(console.error);
    • Create raw transaction object for multisig_payload type txn: the execution of a multisig proposal.

      Give function, functionTypeArgs and functionArgs to execute a proposal that stores only the hash of its payload (create_transaction_with_hash), or to have the node check the payload stored on chain against them. Give none of the three to execute a proposal whose payload is stored on chain (create_transaction); the transaction then carries no payload and the node reads it from the proposal. supra.multisig.executeMultisigTransaction reads the proposal and chooses.

      A transaction without a payload cannot be simulated (transaction.simulate.simple, transaction.simulate.serialized, enableTransactionSimulation when it is submitted): the node refuses with MISSING_DATA.

      Parameters

      • args: {
            senderAddress: AccountAddressInput;
            senderSequenceNumber: bigint;
            multisigAddress: AccountAddressInput;
            function?: `${string}::${string}::${string}`;
            functionTypeArgs?: TypeTag[];
            functionArgs?: Uint8Array<ArrayBufferLike>[];
            optionalTransactionPayloadArgs?: OptionalTransactionPayloadArgs;
        }
        • senderAddress: AccountAddressInput

          Sender account address

        • senderSequenceNumber: bigint

          Sender account sequence number

        • multisigAddress: AccountAddressInput

          Multisig account address

        • Optionalfunction?: `${string}::${string}::${string}`

          Target function name as MoveFunctionId; absent for a proposal whose payload is stored on chain

        • OptionalfunctionTypeArgs?: TypeTag[]

          Target function type args; absent when function is

        • OptionalfunctionArgs?: Uint8Array<ArrayBufferLike>[]

          Target function args; absent when function is

        • OptionaloptionalTransactionPayloadArgs?: OptionalTransactionPayloadArgs

          Optional arguments for transaction payload. This builder makes no request: without a maxGas on the call or the client, the max gas is DEFAULT_MAX_GAS_UNITS (20,000 units). The node requires the sender's SUPRA balance to cover max gas × gas unit price at validation: 20,000 units at a price of 100,000 quants need 20 SUPRA (2,000,000,000 quants). A sender with less must set maxGas. The builder cannot read the node's gas unit price estimate: without a gasUnitPrice on the call or the client it throws a RangeError; supra.getEstimatedGasUnitPrice() returns the estimate.

      Returns ExtendedRawTransaction

      Raw transaction object

      import { BCS, Network, SupraAccount, SupraClient } from "supra-ts-sdk";

      const supra = new SupraClient({ network: Network.TESTNET });
      const account = new SupraAccount(); // an owner of the multisig account, holding SUPRA
      const multisigAccountAddress = "0x1234"; // replace with the address of the multisig account
      const receiverAddress = new SupraAccount().address();

      async function runExample() {

      const supraCoinTransferSerializedMultisigRawTransaction = supra.transaction.build.multisigRawTxnObject({
      senderAddress: account.address(),
      senderSequenceNumber: (await supra.account.getAccountInfo({ accountAddress: account.address() })).sequence_number,
      multisigAddress: multisigAccountAddress,
      function: "0x1::supra_account::transfer",
      functionTypeArgs: [],
      functionArgs: [receiverAddress.toUint8Array(), BCS.bcsSerializeUint64(1000n)],
      optionalTransactionPayloadArgs: { gasUnitPrice: await supra.getEstimatedGasUnitPrice() }
      }).toBytes();

      console.log(supraCoinTransferSerializedMultisigRawTransaction);
      }

      runExample().catch(console.error);
    • Create raw transaction object to create multisig transaction

      Parameters

      • args: {
            senderAddress: AccountAddressInput;
            senderSequenceNumber: bigint;
            multisigAddress: AccountAddressInput;
            function: `${string}::${string}::${string}`;
            functionTypeArgs: TypeTag[];
            functionArgs: Uint8Array<ArrayBufferLike>[];
            optionalTransactionPayloadArgs?: OptionalTransactionPayloadArgs;
        }
        • senderAddress: AccountAddressInput

          Sender account address

        • senderSequenceNumber: bigint

          Sender account sequence number

        • multisigAddress: AccountAddressInput

          Multisig account address

        • function: `${string}::${string}::${string}`

          Target function name as MoveFunctionId

        • functionTypeArgs: TypeTag[]

          Target function type args

        • functionArgs: Uint8Array<ArrayBufferLike>[]

          Target function args

        • OptionaloptionalTransactionPayloadArgs?: OptionalTransactionPayloadArgs

          Optional arguments for transaction payload. This builder makes no request: without a maxGas on the call or the client, the max gas is DEFAULT_MAX_GAS_UNITS (20,000 units). The node requires the sender's SUPRA balance to cover max gas × gas unit price at validation: 20,000 units at a price of 100,000 quants need 20 SUPRA (2,000,000,000 quants). A sender with less must set maxGas. The builder cannot read the node's gas unit price estimate: without a gasUnitPrice on the call or the client it throws a RangeError; supra.getEstimatedGasUnitPrice() returns the estimate.

      Returns ExtendedRawTransaction

      Raw transaction object

      import { BCS, Network, SupraAccount, SupraClient } from "supra-ts-sdk";

      const supra = new SupraClient({ network: Network.TESTNET });
      const account = new SupraAccount(); // an owner of the multisig account, holding SUPRA
      const multisigAccountAddress = "0x1234"; // replace with the address of the multisig account
      const receiverAddress = new SupraAccount().address();

      async function runExample() {

      const supraCoinTransferSerializedMultisigHashedRawTransaction = supra.transaction.build.multisigProposalTxRawTxnObject(
      {
      senderAddress: account.address(),
      senderSequenceNumber: (await supra.account.getAccountInfo({ accountAddress: account.address() })).sequence_number,
      multisigAddress: multisigAccountAddress,
      function: "0x1::supra_account::transfer",
      functionTypeArgs: [],
      functionArgs: [receiverAddress.toUint8Array(), BCS.bcsSerializeUint64(1000n)],
      optionalTransactionPayloadArgs: { gasUnitPrice: await supra.getEstimatedGasUnitPrice() }
      }
      ).toBytes();

      console.log(supraCoinTransferSerializedMultisigHashedRawTransaction);
      }

      runExample().catch(console.error);
    • Create signed transaction payload

      Parameters

      • args: { senderAccount: SupraAccount; rawTxn: RawTransaction }
        • senderAccount: SupraAccount

          Sender KeyPair

        • rawTxn: RawTransaction

          Raw transaction payload

      Returns Promise<SignedTransaction>

      SignedTransaction

      import { BCS, Network, SupraAccount, SupraClient } from "supra-ts-sdk";

      const supra = new SupraClient({ network: Network.TESTNET });
      const account = new SupraAccount(); // an account that holds SUPRA
      const receiverAddress = new SupraAccount().address();

      async function runExample() {

      const supraCoinTransferRawTransaction = supra.transaction.build.rawTxnObject({
      senderAddress: account.address(),
      senderSequenceNumber: (await supra.account.getAccountInfo({ accountAddress: account.address() })).sequence_number,
      function: "0x1::supra_account::transfer",
      functionTypeArgs: [],
      functionArgs: [receiverAddress.toUint8Array(), BCS.bcsSerializeUint64(10000n)],
      optionalTransactionPayloadArgs: { gasUnitPrice: await supra.getEstimatedGasUnitPrice() },
      });

      const signedTransaction = await supra.transaction.build.signedTransaction({
      senderAccount: account,
      rawTxn: supraCoinTransferRawTransaction
      });

      // Convert to SendTxPayload to send transaction
      console.log(signedTransaction);
      }

      runExample().catch(console.error);

      SupraChainIdMismatchError before signing when the client's or the transaction's chain ID is not the node's (see SupraConfig.verifyChainId)

      RangeError before signing when the transaction's expiration time is more than the node's maximum time to live after the current time (the maximum is read once per client; see getTransactionParameters()), and the error of a failed read of that maximum

    • Generate SendTxnPayload using RawTransaction to send transaction request Generated data can be used to send transaction directly using /rpc/v3/transactions/submit endpoint of rpc_node

      Parameters

      • args: { senderAccount: SupraAccount; rawTxn: RawTransaction }
        • senderAccount: SupraAccount

          Sender KeyPair

        • rawTxn: RawTransaction

          Raw transaction data

      Returns Promise<SendTxnPayload>

      SendTxPayload. Its u64 fields are bigint, which JSON.stringify rejects; serialize it with stringifyWithBigInt, which writes them as exact JSON numbers.

      import { BCS, Network, SupraAccount, SupraClient, stringifyWithBigInt } from "supra-ts-sdk";

      const supra = new SupraClient({ network: Network.TESTNET });
      const account = new SupraAccount(); // an account that holds SUPRA
      const receiverAddress = new SupraAccount().address();

      async function runExample() {

      const supraCoinTransferRawTransaction = supra.transaction.build.rawTxnObject({
      senderAddress: account.address(),
      senderSequenceNumber: (await supra.account.getAccountInfo({ accountAddress: account.address() })).sequence_number,
      function: "0x1::supra_account::transfer",
      functionTypeArgs: [],
      functionArgs: [receiverAddress.toUint8Array(), BCS.bcsSerializeUint64(10000n)],
      optionalTransactionPayloadArgs: { gasUnitPrice: await supra.getEstimatedGasUnitPrice() },
      });

      const supraCoinTransferSendTxnPayload = await supra.transaction.build.sendTxnPayload({
      senderAccount: account,
      rawTxn: supraCoinTransferRawTransaction
      });

      let txn = await fetch("https://rpc-testnet.supra.com/rpc/v3/transactions/submit", {
      method: "POST",
      body: stringifyWithBigInt(supraCoinTransferSendTxnPayload),
      headers: {
      "Content-Type": "application/json"
      }
      });

      console.log("Transaction submitted:", await txn.json());

      }

      runExample().catch(console.error);

      SupraChainIdMismatchError before signing when the client's or the transaction's chain ID is not the node's (see SupraConfig.verifyChainId)

      RangeError before signing when the transaction's expiration time is more than the node's maximum time to live after the current time (the maximum is read once per client; see getTransactionParameters()), and the error of a failed read of that maximum