Secret Network
WebsiteDiscordGithub
  • ๐Ÿ‘‹INTRODUCTION
    • Secret Network Introduction
    • Secret Network Techstack
      • Private transactions - A quick summary
      • Blockchain Technology
        • Cosmos Basics
        • Tendermint
        • Cosmos SDK
        • IBC
        • CosmWasm
      • Privacy Technology
        • Encryption - Key Management
          • Overview
          • Key Derivation & Encryption Techniques
          • The Initialization Of Secret Network
          • Full Node Boostrap
          • Contract State Encryption
          • Transaction Encryption
          • Consensus seed rotation
        • Trusted Execution Environmentsโ€Š (TEE) โ€”โ€Š Intel SGX
          • How Secret Network Uses SGX
          • SGX-SPS Security & Reliabillity
          • Remote Attestation
          • Trusted & Untrusted Core
          • Sealing
        • Private smart contracts - overview
  • ๐Ÿ’ปDevelopment
    • ๐Ÿ Getting Started
      • Setting Up Your Environment
        • Cargo.toml Best Practices (Crates vs Dependencies)
      • Compile and Deploy
      • Running the Application
      • Compile and Deploy on Secret testnet (best for Javascript devs)
      • Fullstack dApp Integration
    • ๐Ÿค“Secret Contracts
      • Secret Contracts & CosmWasm
        • Framework overview
        • Secret Contract Components
          • Instantiation Message
          • Execution Message
          • Query Message
          • Deps/DepsMut
          • Storage
            • Prefixed Storage
            • Singleton
            • Keymap
            • Append Store
            • Best practices
        • CosmWasm vs Secret CosmWasm
      • Secret Tokens (SNIP-20)
      • Contract - module call
      • Secret contract - Design Space/Features
        • Secret Contracts introduction
        • Gas/Fee usage
        • TPS and scalability
        • Privacy Essentials
        • Access Control
          • Viewing Keys
          • Permits
        • Trusted and untrusted data
        • Secret-VRF - on-chain Randomness
        • Privacy design
          • Mitigate privacy risks - full guide
          • Gas Evaporation & Tracking
        • Confidential Computing Layer
        • Fiat/Crypto Onboarding
        • Account abstraction
        • Fee abstraction
        • Wallet support
        • Bridge (messaging/tokens)
        • IBC (Hooks, PFM, Wasm)
        • Price Oracles
        • Auto Restaking
      • Permissioned Viewing
        • Viewing Keys
        • Permits
      • Cross Contract Communication
      • Submessages
        • get_contract_code_hash
      • Randomness API - Secret VRF
        • Native On-chain randomness
        • Randomness over IBC
      • Execution Finalization
      • Factory Contracts
      • Contract Migration
        • Manual - < v1.11
        • Native - from v1.11
      • Cross-deploy Vanilla CW and Secret Contracts
      • Testing Secret Contracts
        • Unit Tests
        • Continuous Integration
        • Datatype Handling - Uint, floats etc.
    • ๐Ÿ‘€Secret Contract - Reference, Guides, Examples
      • Starter guide - Millionaire's Problem
      • Reference Contracts
      • Open source dApps
      • Tools & Libraries
        • Network interaction SDKs
          • Secret.js (JavaScript)
          • SecretPy (Python)
          • SecretK (Kotlin)
          • Secret.NET
            • Snippets
              • Deploying a Contract
              • Send Native Coin
              • Query a Contract
              • Create a new Wallet
              • Permits
              • SNIP20
              • SNIP721
          • Shade.Js
        • LocalSecret - Devnet docker
        • Smart contract - Tools/Utils
          • Secret Toolkit
          • CW-Plus
          • Fadroma - SC framework
          • Hidden Gems
          • Other
            • Secret IDE
            • Polar
    • ๐Ÿ–ผ๏ธFrontend Development
      • Getting Started with SecretJS
        • Usage Examples
          • Sending Queries
          • Sending Messages
          • Contract Migration
          • Wallet Integrations
          • Query Permits
          • SNIP20 (SCRT Tokens)
          • SNIP721 (Secret NFTs)
      • Feegrant
        • Understanding Feegrant allowances
        • Grant allowances
        • Using grant allowances to execute transactions
        • Using the Fee Grant Faucet
    • ๐Ÿ“ฌDeployment Addresses/ API Endpoints
      • Secret (SNIP 20) token contracts list
        • SNIP Asset naming guidelines
      • Connecting to the Network
        • API Endpoints Mainnet (Secret-4)
        • API Endpoints Testnet (Pulsar-3)
        • Usage examples
        • Comparison of endpoint types
      • Create your own SNIP-25 IBC Token
  • Secret AI
    • ๐ŸคIntroduction
    • ๐Ÿ—๏ธArchitecture
    • ๐Ÿ‘ฉโ€๐Ÿ’ปSecret AI SDK
      • Setting Up Your Environment
      • Running the Application
    • ๐Ÿช™Economics
    • Smart Contract Reference
      • SubscriptionManager
      • WorkerManager
      • RewardsManager
  • ๐ŸŒSecretVM - Confidential Virtual Machines
    • ๐ŸคIntroduction
    • ๐Ÿ—๏ธArchitecture
    • โ˜‘๏ธAttestation
      • What is Attestation
      • Obtaining Attestation Data
      • Attestation Report - Key Fields
      • Chain of Trust
    • ๐ŸLaunching a SecretVM
    • ๐Ÿ› ๏ธManaging SecretVM Lifecycle
    • โœ…Verifying a SecretVM
      • ๐ŸขFull Verification
      • ๐ŸฐQuick Verification
    • ๐Ÿ‘จโ€๐Ÿ’ปSecretVM CLI
      • Getting started
      • Authentication Commands
      • Virtual Machine Commands
    • ๐Ÿ’กBest Practices for Developers
    • ๐Ÿ”Verifiable Message Signing
    • ๐Ÿ“–Glossary
  • ๐Ÿ”“Confidential Computing Layer
    • ๐Ÿง‘โ€๐Ÿš€IBC Developer Toolkit
      • Basics
        • Overview
        • Cross-chain Messaging with IBC Hooks
          • Functions, Methods, and Data Structures
          • Typescript SDK
          • IBC-Hooks
        • IBC Relaying with Go Relayer
      • Usecases
        • Storing Encrypted Data on Secret Network
          • Key-Value store Developer Tutorial
        • Secret VRF for IBC with IBC-Hooks
        • Confidential Voting
        • Sealed Bid Auctions
      • Supported Networks
        • Mainnet
        • Testnet
    • ๐ŸคEthereum (EVM) Developer Toolkit
      • Basics
        • Overview
        • Connecting Metamask to Secret Network
        • SecretPath + Reown integration
        • Cross-chain Messaging
          • SecretPath
            • Architecture Overview
            • Detailed Architecture
            • SecretPath Developer Tutorials
            • Public EVM Gateway Architecture
            • How to deploy SecretPath on your chain
          • Axelar GMP
            • Architecture Overview
            • Axelar GMP Developer Tutorial
      • Usecases
        • Storing Encrypted Data on Secret Network
          • Key-Value store Developer Tutorial
        • Sealed Bid Auction
          • Sealed Bid Auction Developer Tutorial
        • Confidential Voting
          • Confidential Voting Developer Tutorial with SecretPath
        • VRF
          • Implementing VRF into any EVM Contract
          • VRF Developer Tutorial
          • Performance figures of SecretVRF vs competitors
          • Using encrypted payloads for VRF
          • Converting from Chainlink VRF to Secret VRF in four steps
        • Confidential Document Sharing
        • Tokens
          • From EVM to Secret
      • Supported Networks
        • EVM
          • EVM Mainnet
          • EVM Testnet
          • Gateway Contract ABI
        • Secret Gateway
          • SecretPath mainnet (secret-4) contracts
          • SecretPath testnet (pulsar-3) contracts
    • ๐Ÿ™ŒSolana Developer Toolkit
      • Usecases
        • Storing Encrypted Data on Secret Network
          • Key-value Store Developer Tutorial
        • VRF
          • VRF Developer Tutorial
      • Program IDs
        • Solana Mainnet & Testnet
        • Gateway Contract IDL
  • ๐ŸคซOverview, Ecosystem and Technology
    • ๐Ÿš€Secret Network Overview
      • The SCRT coin
      • Private Tokens
      • Use Cases
        • Decentralized Finance (DeFi)
        • Art And Digital Media
        • Gaming
        • Data Privacy
        • Payments And Transactions
        • Communication
      • The technology
      • History
      • Roadmap (Core development)
        • Secret 2.0
      • Where To Buy SCRT?
      • Using the Testnet
    • ๐ŸธEcosystem Overview
      • Wallets
      • Applications
      • Explorers & tools
      • Funding
        • SCRT Labs Grants
        • Dilutive funding/VC raise
        • Community Pool
        • Developer bounties
          • SCRT Labs bounties [on-hold]
          • CCBL [on-hold]
          • CCR [On-hold]
        • Application specific
          • Shade Grants
      • Contributors & Entities
        • Validators
        • SCRT Labs
        • Secret Foundation
        • Secret Committees
          • Support
          • Governance
      • Secret Network Dictionary
  • ๐Ÿ”งInfrastructure
    • ๐Ÿ”“Use SecretCLI
      • Secretcli vs. Secretd
      • Install
      • Configuration
      • Address Types
      • Key Types
      • Generating Keys
      • Viewing Keys
      • Query Transactions
      • Send Tokens
      • Multisig Keys
      • Multisig Transactions
      • Transaction Broadcasting
      • Fees & Gas
      • Fee Distribution
      • Secret Contracts
      • Slashing
      • Minting
      • Delegating
      • Restake
      • Nodes
      • Governance
        • Creating Governance Proposals
        • Query Proposals
        • Deposits
        • Voting
    • ๐Ÿ”Use Ledger hardware wallet
      • ๐Ÿ”Ledger with SecretCLI
    • ๐Ÿ–ฅ๏ธRunning a node/validator
      • Setting up a node/validator
        • Hardware setup
          • Hardware Compliance
          • VPS/Bare-Metal Compliance
            • Leaseweb Setup
            • PhoenixNAP Setup
            • Psychz Setup
            • nForce Setup
            • Vultr Setup
            • OVHCloud Setup
            • Microsoft Azure Setup
          • Patching your Node
          • Enclave verification
          • Registration troubleshooting
        • Testnet Setup
          • Install SGX
          • Install secretd
          • Setup Full Node
          • Testnet State Sync
          • Becoming a Testnet Validator
          • Installing CLI & Creating A New Address
        • Mainnet Setup
          • Install SGX
          • Install secretd
          • Setup Full Node
          • Quicksync / Snapshot
          • Statesync
          • Becoming A Validator
          • Installing CLI & Creating A New Address
      • Maintaining a node/validator
        • Slashing information
        • Migrating a Validator
        • Troubleshooting
        • Validator Backup
        • Server security
          • SSH authentication
          • Server configuration
          • Uncomplicated-Firewall (UFW)
          • Local CLI
        • Node Monitoring
          • Prometheus
            • Environment Preperation
            • Install Node Exporter
            • Install Prometheus
            • Configuring Prometheus
          • Grafana
            • Install Grafana
            • Grafana Dashboard
            • Next Steps
          • Docker
            • Install Docker
            • Configuration
            • Start Containers
            • Grafana Dashboard
            • Application Ports
            • Stop Containers
          • Goaccess
            • Install Goaccess
            • Setup Goaccess
        • Helpful commands
          • Query Validators
          • Bond Tokens
          • Withdraw Rewards
          • Query Delegations
          • Unbond Tokens
          • Query Unbonding-Delegations
          • Redelegate Tokens
          • Query Redelegations
          • Query Parameters
          • Query Pool
          • Query Delegations To Validator
      • API Noderunning
        • Running Multiple Nodes on the Same Server
        • Node Loadbalancing using Nginx
          • Setup Nginx
          • Example Nginx config
        • Using Auto heal to improve cluster uptime for Nginx
      • Sentry and Archive nodes
        • Mantlemint
        • Sentry Nodes
        • Archive Nodes
    • โ›“๏ธIBC Relayers
      • Hermes
      • RLY
      • IBC channel database
    • ๐Ÿ†™Upgrade Instructions
      • v1.13
      • v1.12
      • v1.11
      • v1.10
      • v1.9
      • v1.8
      • v1.7
      • Shockwave Omega v1.6
      • v1.5
      • Shockwave Delta v1.4
      • Shockwave Delta v1.4 (Testnet)
      • Shockwave Alpha v1.3
      • Cosmovisor
      • Vulcan Network Upgrade (OLD)
    • โ˜ ๏ธPostmortems
      • SNIP-20 leaks
      • xApic
      • Secpk-Verifications Bloat
      • Earn Contract Exploit
      • Testnet Halt 95
    • โœ๏ธContribute to the documentation
      • Report Bugs
      • Suggest Enhancements
      • First Contribution Guide
      • Pull Request Templates
        • Update Documentation
        • Bug Fix
        • Improve Performance
        • Change Functionality
      • Style Guide
    • ๐ŸŒŠVersioning & Changelog
      • Secret Network v1.13
      • Secret Network v1.12
      • Secret Network v1.11
      • Secret Network v1.10
      • Secret network v1.9
      • Secret Network v1.7/1.8
      • Secret Network v1.6
      • Secret Network v1.5
      • Secret Network v1.4 (CosmWasm 1.0)
Powered by GitBook
On this page
  • Overview
  • Understanding SecretPath
  • Secret Network Prerequisites
  • Getting Started with Secret Network
  • Compiling and uploading the Secret contract
  • Send encrypted data to your Secret Contract on the EVM

Was this helpful?

Edit on GitHub
Export as PDF
  1. Confidential Computing Layer
  2. Ethereum (EVM) Developer Toolkit
  3. Usecases
  4. Confidential Voting

Confidential Voting Developer Tutorial with SecretPath

Learn how to use SecretPath to vote confidentially on the EVM

Overview

SecretPath enables EVM developers to use Secret Network as a Confidential Computation Layer (CCL) for all EVM-compatible chains.

In this developer tutorial, you will learn how to use SecretPath to enable confidential voting on the EVM.

See a fullstack cross-chain voting demo here.

Understanding SecretPath

At a high level, you can think of SecretPath as a confidential bridge that passes encrypted data from your EVM chain to a Secret Network smart contract where the data remains encrypted.

To work with SecretPath, you must first create a Secret smart contract that stores the encrypted data that you want to send from the EVM. For our purposes, we have created a Secret smart contract with 2 functionalities:

  1. Create proposals

  2. Vote on existing proposals

You create and vote on proposals from the EVM, and then that data is sent to your Secret smart contract via SecretPath where it remains encrypted . Pretty cool, right!? ๐Ÿ˜Ž Let's start by examining our Secret voting contract, and then we will breakdown how to send messages to it from the EVM with SecretPath.

Secret Network Prerequisites

  1. Add Secret Network testnet to Keplr.

  2. Fund your Secret testnet wallet.

Getting Started with Secret Network

To get started, clone the examples repo:

git clone https://github.com/writersblockchain/secretpath-voting.git

cd into secretpath-tutorials/secretpath-voting/voting-contract:

cd secretpath-voting/voting-contract

Open contract.rs and examine the match statement at line 67:

match handle {
        "create_proposal" => create_proposal(deps, env, msg.input_values, msg.task, msg.input_hash),
        "create_vote" => create_vote(deps, env, msg.input_values, msg.task, msg.input_hash),

        _ => Err(StdError::generic_err("invalid handle".to_string())),
    }

This handle msg is where you define the functionality of your SecretPath contract. For our purposes, we have written the functions create_proposal and create_vote. You can examine those functions in more detail if you'd like and make adjustments as you see fit ๐Ÿค“.

Compiling and uploading the Secret contract

Update the env file with your Secret Network wallet mnemonic, and rename it ".env" instead of ".env.example"

Compile the contract

make build-mainnet

cd into voting-contract/node:

cd node

Install the node dependencies

npm install

Set SecretPath parameters:

Open upload.js and configure the SecretPath gatewayAddress, gatewayHash, and gatewayPublicKey:

const gatewayAddress = "secret10ex7r7c4y704xyu086lf74ymhrqhypayfk7fkj";

const gatewayHash =
 "ad8ca07ffba1cb26ebf952c29bc4eced8319c171430993e5b5089887f27b3f70";

const gatewayPublicKey =
"0x046d0aac3ef10e69055e934ca899f508ba516832dc74aa4ed4d741052ed5a568774d99d3bfed641a7935ae73aac8e34938db747c2f0e8b2aa95c25d069a575cc8b";

gatewayAddress, gatewayHash, and gatewayPublicKey are needed for instantiating contracts that utilize SecretPath and can be found in the docs here. You will always use these same 3 parameters for instantiating a SecretPath-compatible contract on testnet.

Upload and instantiate the contract:

node upload

Upon successful upload and instantiation, add the contract codeHash and address to your env.

Send encrypted data to your Secret Contract on the EVM

Now that you have instantiated your confidential voting contract on Secret Network, it's time to pass your encrypted data from the EVM to Secret Network. Remember the create_proposal and create_vote functions from the Secret contract? Now you will execute those functions and send encrypted data to the voting contract! ๐Ÿคฏ

Bootstrapping the frontend

Let's create and vote on your first proposal with SecretPath!

cd into secretpath-voting/frontend:

cd secretpath-voting/frontend

Install the dependencies

npm i

Configure env

Configure the envwith your confidential voting contractAddress and codeHash.

Run the application

npm run start

You should see the following React application running locally in the browser:

Now, create and vote on a proposal to understand the frontend functionality. Then, let's look at the underlying code to understand how we are passing encrypted data from the EVM to Secret Network ๐Ÿ™‚

Passing Encrypted Data with SecretPath

As stated above, we have two functions we are executing with SecretPath: create_proposal and create_vote. In our React application, there are two corresponding components which execute these functions: CreateProposal and VoteonProposal.

Create a Voting Proposal

Open CreateProposal.js and navigate to the handleSubmit function, which contains all of our SecretPath logic.

The majority of the handleSubmit function is boilerplate code used for SecretPath verification, signing, and converting contract inputs into correctly formatted packets and vice versa.

For our purposes, we only need to examine 2 lines of code, data on line 88 and handle on line 218.

  1. data is the encrypted data that we are passing from the EVM to the Secret Network voting contract. It takes a user input of name, description, and end_time. This corresponds with the ProposalStoreMsg in the Secret contract.

  2. handle is the function that is actually being called in the Secret contract that you deployed. You are passing the create_proposal handle, which executes the create_proposal function in your Secret voting contract.

Now that you have all of your SecretPath code configured, execute the frontend to send your voting proposal to the Secret contract!

Upon successful execution, your SecretPath transaction hash will be logged in the console.

Vote on a Proposal

Open VoteonProposal.js and navigate to the handleSubmit function, which, again, contains all of our SecretPath logic.

  1. data is the encrypted data that we are passing from the EVM to the Secret Network voting contract. It takes a user input of vote, ("yes" or "no"), wallet_address (the wallet address of the voter), and index.This corresponds with the VoteStoreMsg in the Secret contract.

The voting contract is designed so that each proposal has an ascending index starting with 1. The first proposal you create is index 1, the second is index 2, etc. So when you vote, the React application passes the corresponding index of the proposal that is to be voted on ๐Ÿ™‚

  1. handle: You are passing the create_vote handle, which executes the create_vote function in your Secret voting contract.

Execute the frontend to vote on an existing proposal and send the encrypted vote to the Secret contract!

Upon successful execution, your SecretPath transaction hash will be logged in the console.

Secret Queries - retrieving proposals and votes from Secret contract storage

Perhaps you are wondering how the React frontend queries the Secret voting contract to display the data that we pass from the EVM. This is possible with secret.js, the javascript SDK for Secret Network.

We have 2 query functions defined in our Secret voting contract, RetrieveProposals and RetrieveVotes. Once you have created proposals with votes, you can use execute these query functions with secret.js to:

  1. Query all proposals

  2. Query all votes

These queried proposals and their associated votes are then displayed in our React frontend.

Conclusion

Congrats! You deployed your very own confidential voting contract on Secret Network and used SecretPath to send cross-chain encrypted votes on an EVM chain. See the fullstack demo here. You now have all of the tools you need to start building your own cross-chain SecretPath contracts on the EVM ๐ŸŽ‰

Note: the end user of the application is not exposed to Secret Network and is only working directly in the EVM environment. However, the data is fully protected and cannot be viewed by anyone because it is stored in encrypted Secret contracts ๐Ÿ˜ฎโ€๐Ÿ’จ

If you have any questions or run into any issues, post them on the Secret Developer Discord and somebody will assist you shortly.

SecretPath - a deep dive

Let's dive a little deeper into the boilerplate SecretPath code to understand how our data is encrypted, signed, and formatted by SecretPath. The following comments are for the handleSubmit function of our CreateProposal component:

// Load the contract ABI into an ethers Interface.
const iface = new ethers.utils.Interface(abi);

// Load routing contract address and code hash from environment variables.
const routing_contract = process.env.REACT_APP_SECRET_ADDRESS;
const routing_code_hash = process.env.REACT_APP_CODE_HASH;

// Connect to the Ethereum network through a web provider (e.g., MetaMask).
const provider = new ethers.providers.Web3Provider(window.ethereum, "any");

// Request user accounts from the Ethereum provider.
const [myAddress] = await provider.send("eth_requestAccounts", []);

// Generate a new random wallet and extract private key and public key.
const wallet = ethers.Wallet.createRandom();
const userPrivateKeyBytes = arrayify(wallet.privateKey);
const userPublicKey = new SigningKey(wallet.privateKey).compressedPublicKey;
const userPublicKeyBytes = arrayify(userPublicKey);

// Hardcoded public key for the gateway and conversion to bytes.
const gatewayPublicKey = "A20KrD7xDmkFXpNMqJn1CLpRaDLcdKpO1NdBBS7VpWh3";
const gatewayPublicKeyBytes = base64_to_bytes(gatewayPublicKey);

// Compute a shared key using Elliptic Curve Diffie-Hellman (ECDH) and hash it with SHA-256.
const sharedKey = await sha256(
  ecdh(userPrivateKeyBytes, gatewayPublicKeyBytes)
);

// Get the selector (method ID) for the `upgradeHandler` function from the ABI.
const callbackSelector = iface.getSighash(
  iface.getFunction("upgradeHandler")
);
const callbackGasLimit = 300000;  // Set the gas limit for the callback.

// Create the data object from form state for payload.
const data = JSON.stringify({
  name: name,
  description: description,
  end_time: minutes,
});

// Determine the appropriate client address based on the network (chainId).
let publicClientAddress;

// Mainnet client addresses by chain ID.
if (chainId === "1") { publicClientAddress = mainnet.publicClientAddressEthereumMainnet; }
// Add similar conditions for other chain IDs, both mainnet and testnet.

// Lowercase the client address to ensure consistency.
const callbackAddress = publicClientAddress.toLowerCase();

// Log relevant information.
console.log("callback address: ", callbackAddress);
console.log(data);
console.log(callbackAddress);

// Construct the payload with necessary information for processing.
const payload = {
  data: data,
  routing_info: routing_contract,
  routing_code_hash: routing_code_hash,
  user_address: myAddress,
  user_key: bytes_to_base64(userPublicKeyBytes),
  callback_address: bytes_to_base64(arrayify(callbackAddress)),
  callback_selector: bytes_to_base64(arrayify(callbackSelector)),
  callback_gas_limit: callbackGasLimit,
};

// Serialize the payload to JSON and prepare it for encryption.
const payloadJson = JSON.stringify(payload);
const plaintext = json_to_bytes(payload);
const nonce = crypto.getRandomValues(bytes(12)); // Generate a nonce for encryption.

// Encrypt the payload using ChaCha20-Poly1305, obtain the ciphertext and authentication tag.
const [ciphertextClient, tagClient] = chacha20_poly1305_seal(
  sharedKey,
  nonce,
  plaintext
);
const ciphertext = concat([ciphertextClient, tagClient]);

// Compute the hashes of the ciphertext and prepare it for signature.
const ciphertextHash = keccak256(ciphertext);
const payloadHash = keccak256(
  concat([
    text_to_bytes("\x19Ethereum Signed Message:\n32"),
    arrayify(ciphertextHash),
  ])
);

// Sign the payload hash using the user's account.
const msgParams = ciphertextHash;
const params = [myAddress, msgParams];
const method = "personal_sign";
const payloadSignature = await provider.send(method, params);

// Recover public key from the signature to verify it.
const user_pubkey = recoverPublicKey(payloadHash, payloadSignature);

// Bundle info for the transaction.
const _info = {
  user_key: hexlify(userPublicKeyBytes),
  user_pubkey: user_pubkey,
  routing_code_hash: routing_code_hash,
  task_destination_network: "pulsar-3",
  handle: "create_proposal",
  nonce: hexlify(nonce),
  payload: hexlify(ciphertext),
  payload_signature: payloadSignature,
  callback_gas_limit: callbackGasLimit,
};

// Encode the transaction data using the interface.
const functionData = iface.encodeFunctionData("send", [
  payloadHash,
  myAddress,
  routing_contract,
  _info,
]);

// Fetch the current gas price and calculate the transaction cost.
const gasFee = await provider.getGasPrice();
let amountOfGas;
if (chainId === "4202") {
  amountOfGas = gasFee.mul(callbackGasLimit).mul(100000).div(2);
} else {
  amountOfGas = gasFee.mul(callbackGasLimit).mul(3).div(2);
}

// Set up transaction parameters.
const tx_params = {
  gas: hexlify(150000),
  to: publicClientAddress,
  from: myAddress,
  value: hexlify(amountOfGas),
  data: functionData,
};

// Send the transaction and handle the response.
try {
  const txHash = await provider.send("eth_sendTransaction", [tx_params]);
  console.log(`Transaction Hash: ${txHash}`);

  setIsModalVisible(true); // Show the modal on success
} catch (error) {
  console.error("Error submitting transaction:", error);
}
PreviousConfidential VotingNextVRF

Last updated 7 months ago

Was this helpful?

๐Ÿ”“
๐Ÿค
Cross-chain EVM voting frontend