Skip to content

Instantly share code, notes, and snippets.

@cordt-sei
Last active November 14, 2024 13:18
Show Gist options
  • Save cordt-sei/de629abd98f761fa4cde6a02f485ba53 to your computer and use it in GitHub Desktop.
Save cordt-sei/de629abd98f761fa4cde6a02f485ba53 to your computer and use it in GitHub Desktop.

SEI FAQ

"associate wallet" methods

Updates and complete methods here

Concept / method for associating a wallet address

any strange / unexplainable tx failures are very likely due to not having "associated"* or "linked"* the wallet yet

* This is a term describing the act of making the wallet's pubkey known to the chain so that it can be confirmed that both addresses exist and can be safely used in interoperability functions.

MUST "associate_address" before interacting with pointer contract doing literally any EVM tx

export const associateAddr = async (signature: Hex, message: string, client: UsePublicClientReturnType) => {
    if (!client) {
        throw new Error('Failed to associate. Client is not defined.');
    }
    const { r, s } = secp256k1.Signature.fromCompact(signature.slice(2, 130));
    const v = hexToNumber(`0x${signature.slice(130)}`);

    const messageLength = Buffer.from(message, 'utf8').length;
    const messageToSign = `\x19Ethereum Signed Message:\n${messageLength}${message}`;
    const request: AssociateRequest = { r: numberToHex(r), s: numberToHex(s), v: numberToHex(v - 27), custom_message: messageToSign };
    await client.request<AssociateRequestSchema>({ method: 'sei_associate', params: [request] });
};

You can easily extract the v/r/s from a signed message using the 'ethers' library:

const ethers = require('ethers');

// Example pre-signed transaction data (replace with your actual data)
const signedTxData = <raw_signed_message_here>;

// Remove '0x' prefix if present
const rawData = signedTxData.startsWith('0x') ? signedTxData.slice(2) : signedTxData;

// Extract v, r, s from the raw data
const v = parseInt(rawData.slice(-2), 16); // last byte
const r = '0x' + rawData.slice(0, 64); // first 32 bytes
const s = '0x' + rawData.slice(64, 128); // next 32 bytes

console.log('v:', v);
console.log('r:', r);
console.log('s:', s);

Using something like the example above, sign an empty bytes payload with the wallet to be 'associated', extract the v,r,s signature values and broadcast it using this EVM RPC method:

curl --request POST --url http://127.0.0.1:8545 --header 'accept: application/json' --header 'content-type: application/json' --data ' { "id": 1, "jsonrpc": "2.0", "method": "sei_associate", "params": [ { "r": "0x7c6d0be72bdff972210ce86783afbadeb3739101ac0e6b64b3fda64ddc7285ef", "s": "0x378f0312476380d690999480fba3b80bcb8912781974ccde9c298d7dd18c803c", "v": "0x1" } ] }

https://www.docs.sei.io/dev-advanced-concepts/evm-rpc-endpoints#sei_associate


"associated wallet" query

check for 'associated' address for a given wallet, if exists
$ curl -X POST "$SEIEVM" -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"sei_getEVMAddress","params":["${bech32Address}"],"id":1}'

exp. result {"jsonrpc":"2.0","id":1,"result":"0x..."}

$ curl -X POST "$SEIEVM" -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"sei_getSeiAddress","params":["${hexAddress}"],"id":1}'

exp. result {"jsonrpc":"2.0","id":1,"result":"sei1..."}


API for finding "cross-environment" tx hash

Fetches Tendermint tx hash for corresponding EVM tx hash, or vice versa
curl "$SEIEVM" \
-X POST \
-H "Content-Type: application/json" \
--data '{"method":"sei_getCosmosTx","params":["<evm_tx_hash>"],"id":1,"jsonrpc":"2.0"}'
curl "$SEIEVM" \
-X POST \
-H "Content-Type: application/json" \
--data '{"method":"sei_getEvmTx","params":["<sei1_tx_hash>"],"id":1,"jsonrpc":"2.0"}'

min gas prices

hard-coded amounts

EVM - 100gwei
native - 0.02usei


estimate gas

EVM method

assuming the following parameters:

  • from: 0x1234567890abcdef1234567890abcdef12345678 (sender's address)
  • to: 0xabcdef1234567890abcdef1234567890abcdef12 (recipient's address)
  • gas: 21000 (gas limit)
  • gasPrice: 5000000000 (gas price in Wei)
  • value: 1000000000000000000 (1 ETH in Wei)
  • input: 0x (empty data for a simple ETH transfer)
  • block: "latest" (most recent block)

construct curl request

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_estimateGas","params":[{"from": "0x1234567890abcdef1234567890abcdef12345678", "to": "0xabcdef1234567890abcdef1234567890abcdef12", "gas": "0x5208", "gasPrice": "0x12a05f200", "value": "0xde0b6b3a7640000", "input": "0x"}],"id":1}' -H "Content-Type: application/json" "$SEIEVM"

expected response

{
  "id": 1,
  "jsonrpc": "2.0",
  "result": "0x5208" // Estimated gas in hex (21000)
}
Native/Cosmos method

Parameters

  • body: A string representing the transaction details to simulate. This includes the type of transaction, messages, signatures, fee, and any other required metadata formatted as a serialized string in Protobuf format.

working example

import { getQueryClient } from '@sei-js/cosmjs'; // Import the getQueryClient method from sei-js

// Initialize the query client by connecting to the RPC endpoint of your choice
const queryClient = await getQueryClient("YOUR_RPC_URL");

// Destructure the simulation method from the transaction module
const { eCosmosTxV1Beta1Simulate } = queryClient.cosmos.tx.v1beta1;

// Define the parameters for the simulation
const params = { 
  body: "<Serialized_Transaction_Body>" // Replace with the actual serialized transaction body
};

// Call the simulate method and wait for the response
const response = await eCosmosTxV1Beta1Simulate(params);

// Log the response to see the simulation result
console.log(response);

usage

  • Replace "YOUR_RPC_URL" with the actual RPC endpoint URL of the Cosmos SDK-compatible chain you are working with.

  • Set the body field in the params object to the serialized transaction details (the Protobuf format string that represents your transaction). This should include all necessary transaction details like messages, signatures, and metadata.

  • Execute the code and get the simulation result, which will include details such as the estimated gas required for the transaction. The response can be used to determine if the transaction will likely succeed or if adjustments are needed.

notes

  • getQueryClient("YOUR_RPC_URL"): This function creates a client instance connected to the provided Cosmos SDK RPC URL (YOUR_RPC_URL). This client is required to query the network and simulate transactions.

  • params: This is the request object passed to eCosmosTxV1Beta1Simulate. It must contain the serialized transaction data (in Protobuf format) as the body. This serialized string represents the transaction details you want to simulate.

expected response

The response object returned from eCosmosTxV1Beta1Simulate will include:

  • gas_info: Information about the estimated gas usage.
  • result: The outcome of the simulation, including any logs

, errors, or other data relevant to the transaction.


query for "synthetic" or "echoed" events

Fetching specific Tendermint events from EVM client

In certain scenarios it's possible to prefix the Tendermint tx hash with 0x and pull event logs from it as if it were an EVM tx. This is to save the trouble of separately querying the Tendermint RPC or indexing events from that environment.

The following query should return any relevant Cosmos >> EVM actions related to CW pointer or direct CW20/721 interactions from the EVM side

# tendermint hash
base_hash="a5443495286d4ec8fe83037220ad3b9b7cea02fed2a42d62cfded14403a654e4"

# hash to uppercase (if necessary) and prefix with '0x'
prefixed_hash="0x$(echo "$base_hash" | tr '[:lower:]' '[:upper:]')"

# curl request with formatted json output
curl --location --request POST "$SEIEVM" \
     --header 'Content-Type: application/json' \
     --data "{\"jsonrpc\": \"2.0\",\"method\": \"eth_getTransactionReceipt\",\"params\":[\"$prefixed_hash\"],\"id\":\"test\"}" | jq

Querying pointers/pointees

Querying pointer or pointee by address/denom for relevant assets

Comprehensive Pointer and Pointee API queries

Overview

The Sei Network uses specific endpoints to query token information. You can query either:

  1. Pointers: Addresses representing specific tokens on the Sei Network.
  2. Pointees: The underlying addresses or references associated with a particular token (e.g., ERC20, ERC721, CW20, CW721).

Token Types and Their Use Cases

Token Type pointerType Value Description Use Case
ERC20 0 Represents fungible tokens that adhere to the ERC20 standard on Ethereum or compatible networks. Use to find the Sei address representing an ERC20 token.
ERC721 1 Represents non-fungible tokens (NFTs) adhering to the ERC721 standard. Use to find the Sei address representing an ERC721 token (NFT).
NATIVE 2 Represents native tokens of the Sei Network (e.g., IBC assets). Use to find the pointer for a native asset within the Sei Network.
CW20 3 Represents fungible tokens on the CosmWasm standard, similar to ERC20 but for Cosmos-based chains. Use to find the Sei address representing a CW20 token.
CW721 4 Represents non-fungible tokens on the CosmWasm standard, similar to ERC721 but for Cosmos-based chains. Use to find the Sei address representing a CW721 token (NFT).

How to Use Queries

1. Querying a Pointer

A pointer query retrieves the Sei Network representation (address) of a token by providing the token type and its original address or identifier.

REST Endpoint for Pointer Query:

$SEIREST/sei-protocol/seichain/evm/pointer

Parameters:

  • pointerType: Indicates the token type (use values 0, 1, 2, 3, or 4 as described above).
  • pointee: The original address or identifier for the token.

Example Queries:

  • ERC20 Token:

    curl "$SEIREST/sei-protocol/seichain/evm/pointer?pointerType=0&pointee=0x809FF4801aA5bDb33045d1fEC810D082490D63a4"
  • CW20 Token:

    curl "$SEIREST/sei-protocol/seichain/evm/pointer?pointerType=3&pointee=sei1eavtmc4y00a0ed8l9c7l0m7leesv3yetcptklv2kalz4tsgz02mqlvyea6"

2. Querying a Pointee

A pointee query retrieves the original address or identifier for a token that has a corresponding Sei Network address (pointer). This is useful for finding the relationship between the Sei Network address and its original token reference.

REST Endpoint for Pointee Query:

$SEIREST/sei-protocol/seichain/evm/pointee

Parameters:

  • pointerType: Indicates the token type (use values 0, 1, 2, 3, or 4 as described above).
  • pointer: The Sei Network address of the token.

Example Queries:

  • ERC20 Token:

    curl "$SEIREST/sei-protocol/seichain/evm/pointee?pointerType=0&pointer=sei15ulpjml9ddyyupy9sawwc7wnmnzfl44jyg3j43e4vy5cfwgunh8qfhag22"
  • CW721 Token:

    curl "$SEIREST/sei-protocol/seichain/evm/pointee?pointerType=4&pointer=sei1k2nk8fzdn0s06ev8f3nswuh3ecd6xuznfn906tya02qwlf95lkmqera3qz"

Example Responses

For a successful query, you can expect a response similar to:

Querying a Pointee:

{
  "pointee": "0x809FF4801aA5bDb33045d1fEC810D082490D63a4",
  "version": 2,
  "exists": true
}

Querying a Pointer:

{
  "pointer": "sei15ulpjml9ddyyupy9sawwc7wnmnzfl44jyg3j43e4vy5cfwgunh8qfhag22",
  "version": 2,
  "exists": true
}

Summary of Use Cases

  • Pointer Queries: Use when you have the original token address and need to find its representation on the Sei Network.
  • Pointee Queries: Use when you have the Sei Network address and need to find the original token address or identifier.

Reference for cross-environment Data Searchers

Defines key parameters / properties used in datasources

Unified Table of Equivalent Fields

EVM Field Cosmos/Tendermint Field Description
fact_transactions.hash fact_transactions.txhash Unique identifier of the transaction
fact_transactions.block_number fact_transactions.height Block number containing the transaction
fact_transactions.from_address fact_transactions.sender Address initiating the transaction
fact_transactions.to_address fact_transactions.recipient Address receiving the transaction
fact_transactions.value fact_transactions.amount Amount of native token transferred
fact_transactions.gas_price fact_transactions.gas_price Price of gas for the transaction
fact_transactions.gas_used fact_transactions.gas_used Amount of gas used by the transaction
fact_transactions.input_data fact_transactions.msg_content Input data for the transaction
fact_transactions.status fact_transactions.status Status of the transaction (success/failure)
fact_transactions.nonce fact_transactions.sequence Transaction nonce (sequence number)
fact_transactions.tx_fee fact_transactions.fee Fee paid for the transaction
fact_blocks.number fact_blocks.height Block number/height
fact_blocks.hash fact_blocks.hash Unique identifier of the block
fact_blocks.parent_hash fact_blocks.previous_block_hash Hash of the previous block
fact_blocks.timestamp fact_blocks.timestamp Timestamp of block creation
fact_blocks.gas_used fact_blocks.gas_used Total gas used in the block
fact_blocks.gas_limit fact_blocks.gas_limit Gas limit for the block
fact_blocks.tx_count fact_blocks.num_txs Number of transactions in the block
fact_token_transfers.token_address fact_transfers.token_id Address/ID of the token transferred
fact_token_transfers.from_address fact_transfers.from_address Address sending the tokens
fact_token_transfers.to_address fact_transfers.to_address Address receiving the tokens
fact_token_transfers.value fact_transfers.amount Amount of tokens transferred
fact_event_logs.address fact_msg_attributes.contract_address Address of the contract emitting the event
fact_event_logs.topics fact_msg_attributes.attribute_key Indexed event parameters
fact_event_logs.data fact_msg_attributes.attribute_value Non-indexed event data
dim_contracts.address fact_msg_attributes.contract_address Address of the deployed contract

Fields Specific to Cosmos/Tendermint (No EVM Equivalent)

Cosmos/Tendermint Field Description
fact_transactions.memo Memo attached to the transaction
fact_msgs.msg_type Type of the message
fact_msgs.msg_index Index of the message in the transaction
fact_msgs.msg_content Content of the message in JSON format
dim_tokens.denom Denomination of the token
dim_tokens.decimal Number of decimal places for the token
fact_blocks.proposer_address Address of the block proposer
fact_msg_attributes.msg_index Index of the message generating the attribute
fact_transfers.denom Denomination of the transferred token

Fields Specific to EVM (No Cosmos/Tendermint Equivalent)

EVM Field Description
fact_transactions.tx_fee_precise Precise fee paid for the transaction
fact_transactions.r R component of the transaction signature
fact_transactions.s S component of the transaction signature
fact_transactions.v V component of the transaction signature
dim_contracts.bytecode Bytecode of the contract
dim_contracts.abi ABI (Application Binary Interface) of the contract
fact_traces.trace_address Address of the trace in the call tree
fact_traces.subtraces Number of subtraces
fact_traces.trace_type Type of the trace (call, create, suicide)
fact_event_logs.log_index Index of the log within the transaction
fact_event_logs.transaction_index Index of the transaction within the block
fact_blocks.difficulty Mining difficulty of the block
fact_blocks.total_difficulty Total difficulty up to this block
fact_blocks.size Size of the block in bytes
fact_token_transfers.log_index Index of the transfer event log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment