Seeking correct code of sending SUI (NodeJs)

in witness-category •  yesterday 

I am working on steem2sui - but currently stuck at the last bit of sending SUI - my nodejs code doesn't work - and I can't figure out what is the correct way to send. If you happen to know, that'll be great. Thanks.

The following doesn't work. I've asked chatgpt to iterate a few versions, but none of them work.

async function sendSuiTransaction(sender, recipient, amount, gasBudget, privateKey) {
  try {
    // Validate and decode private key
    if (!privateKey.startsWith("suiprivkey")) {
      throw new Error("Invalid SUI private key: missing 'suiprivkey' prefix.");
    }
    const decoded = bech32.decode(privateKey);
    let privateKeyBytes = Buffer.from(bech32.fromWords(decoded.words));
    if (privateKeyBytes.length === 33) {
      privateKeyBytes = privateKeyBytes.slice(0, 32);
    }
    if (privateKeyBytes.length !== 32) {
      throw new Error("Invalid private key length: expected 32 bytes.");
    }

    // Generate keypair
    const keyPair = Ed25519Keypair.fromSecretKey(privateKeyBytes);

    // Set up provider
    const provider = new JsonRpcProvider(
      new Connection({ fullnode: QUICKNODE_URL })
    );

    // Build transaction
    const tx = new TransactionBlock();
    const [coin] = tx.splitCoins(tx.gas, [tx.pure(amount)]);
    tx.transferObjects([coin], tx.pure(recipient));
    tx.setSender(sender);
    tx.setGasBudget(gasBudget);

    // Build transaction bytes
    const txBytes = await tx.build({ provider });

    // Create intent message (required for SUI signing)
    const intent = new Uint8Array([0, 0, 0]); // Intent: TransactionData, version 0, app 0
    const messageToSign = new Uint8Array([...intent, ...txBytes]);

    // Sign the transaction
    const signatureBytes = keyPair.signData(messageToSign);

    // Prepend signature scheme (0x0 for Ed25519) and encode to Base64
    const signatureWithScheme = new Uint8Array([0x0, ...signatureBytes]);
    const signatureBase64 = toB64(signatureWithScheme);

    // Send the transaction via RPC
    const response = await axios.post(QUICKNODE_URL, {
      method: "sui_executeTransactionBlock",
      jsonrpc: "2.0",
      id: 1,
      params: [
        toB64(txBytes),     // Transaction bytes in Base64
        [signatureBase64],  // Signature with scheme in Base64 array
        { showEffects: true }, // Options
      ],
    });

    console.log("Transaction Result:", response.data);
    return response.data.result;
  } catch (error) {
    console.error("Error sending SUI transaction:", error.response ? error.response.data : error.message);
  }
}

Steem to the Moon🚀!

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!