Coder Social home page Coder Social logo

celo-org / viem Goto Github PK

View Code? Open in Web Editor NEW

This project forked from wevm/viem

0.0 1.0 0.0 356.22 MB

TypeScript Interface for Ethereum

Home Page: https://viem.sh

License: Other

JavaScript 0.02% TypeScript 91.02% CSS 0.01% HTML 0.01% Solidity 6.79% Makefile 0.01% Nix 0.01% MDX 2.15%

viem's Introduction


viem logo

TypeScript Interface for Ethereum

Version Code coverage MIT License Downloads per month Best of JS


Features

  • Abstractions over the JSON-RPC API to make your life easier
  • First-class APIs for interacting with Smart Contracts
  • Language closely aligned to official Ethereum terminology
  • Import your Browser Extension, WalletConnect or Private Key Wallet
  • Browser native BigInt, instead of large BigNumber libraries
  • Utilities for working with ABIs (encoding/decoding/inspection)
  • TypeScript ready (infer types from ABIs and EIP-712 Typed Data)
  • First-class support for Anvil, Hardhat & Ganache
  • Test suite running against forked Ethereum network

... and a lot more.

Overview

// 1. Import modules.
import { createPublicClient, http } from 'viem';
import { mainnet } from 'viem/chains';

// 2. Set up your client with desired chain & transport.
const client = createPublicClient({
  chain: mainnet,
  transport: http(),
});

// 3. Consume an action!
const blockNumber = await client.getBlockNumber();

Documentation

Head to the documentation to read and learn more about viem.

Community

Check out the following places for more viem-related content:

Support

Sponsors

paradigm logo
family logo context logo WalletConnect logo zksync logo PartyDAO logo Dynamic logo Sushi logo Stripe logo Privy logo pancake logo celo logo pimlico logo zora logo lattice logo supa logo syndicate logo reservoir logo brave logo

Contributing

If you're interested in contributing, please read the contributing docs before submitting a pull request.

Authors

License

MIT License

viem's People

Contributors

jxom avatar github-actions[bot] avatar tmm avatar fubhy avatar holic avatar izayl avatar roninjin10 avatar margalit avatar ezynda3 avatar abs3ntdev avatar dependabot[bot] avatar unholypanda avatar 0xolias avatar tateb avatar avasisht23 avatar jeanregisser avatar aaronmgdr avatar rkalis avatar pengdeng-cyber avatar 0xardy avatar clockride avatar alexfertel avatar malonehedges avatar songkeys avatar arthurgousset avatar zkgggggame avatar omahs avatar nikola-bozin-txfusion avatar bjfresh avatar wighawag avatar

Watchers

 avatar

viem's Issues

bug: `contract.simulate` does not accept `feeCurrency` field

Is there an existing issue for this?

  • I have searched the existing issues

Package Version

2.7.9

Current Behavior

This code snippet shows an error (red squiggly line) under feeCurrency:

const transactionSimulation = await contract.simulate.transfer(
        [cUSD_CONTRACT_ADDRESS, parseUnits("0.01", decimals)],
        { account: sender, feeCurrency: "0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1" }
);

The error message is:

Object literal may only specify known properties, and 'feeCurrency' does not exist in type 'Omit<SimulateContractParameters<readonly ...

But the same code as contract.write.transfer accepts the feeCurrency

const transactionReceipt = await contract.write.transfer(
        [cUSD_CONTRACT_ADDRESS, parseUnits("0.01", decimals)],
        { account: sender, feeCurrency: "0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1" }
    );

Expected Behavior

simulate and WalletClient calls should accept the same fields.

Viem recommends that most contract calls or transactions are first simulated

Warning: The write internally sends a transaction โ€“ it does not validate if the contract write will succeed (the contract may throw an error). It is highly recommended to simulate the contract write with `contract.simulate` before you execute it.

Steps To Reproduce

import {
    createPublicClient,
    createWalletClient,
    http,
    parseEther,
    parseGwei,
    Address,
    getContract,
    erc20Abi,
    parseUnits,
    formatUnits,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { celoAlfajores } from "viem/chains";
import {
    PRIVATE_KEY,
    RECIPIENT,
    cUSD_CONTRACT_ADDRESS,
    USDC_CONTRACT_ADDRESS,
    USDC_ADAPTER_ADDRESS,
} from "./constants";

/**
 * Boilerplate to create a viem client and viem-compatible wallet
 */
const read = createPublicClient({
    chain: celoAlfajores,
    transport: http(),
});
const write = createWalletClient({
    chain: celoAlfajores, // Celo testnet
    transport: http(),
});
const sender = privateKeyToAccount(`0x${PRIVATE_KEY}`);

/**
 *  Set up ERC20 contract
 */
const contract = getContract({
    address: cUSD_CONTRACT_ADDRESS,
    abi: erc20Abi,
    client: { public: read, wallet: write },
});
const [symbol, decimals, tokenBalance] = await Promise.all([
    contract.read.symbol(),
    contract.read.decimals(),
    contract.read.balanceOf(["0xcEe284F754E854890e311e3280b767F80797180d"]),
]);

/**
 * Makes a transaction to transfer ERC20 tokens using a fee currency
 */
async function erc20Transfer() {
    console.log(`Initiating fee currency transaction...`);
    console.log(`${symbol} balance of ${sender}: ${formatUnits(tokenBalance, decimals)}`);

    const transactionSimulation = await contract.simulate.transfer(
        [RECIPIENT, parseUnits("0.01", decimals)],
        { account: sender, feeCurrency: "0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1" }
    );
    const transactionReceipt = await contract.write.transfer(
        [RECIPIENT, parseUnits("0.01", decimals)],
        { account: sender, feeCurrency: "0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1" }
    );
    console.log(transactionReceipt);
}

erc20Transfer().catch((err) => {
    console.error("An error occurred:", err);
});

Link to Minimal Reproducible Example (StackBlitz, CodeSandbox, GitHub repo etc.)

https://github.com/celo-org/feecurrency/blob/main/viem.ts

Anything else?

No response

Related

Add celo gas fee estimator

Is there an existing issue for this?

  • I have searched the existing issues

Package Version

1.0.0

Current Behavior

when using feeCurrency it is necessary to lookup gasPrice by hand as the automatic way does not factor in feeCurrency

Expected Behavior

Add a celo estimateFeesPerGas function

internally this should call eth_gasPrice with feeCurrency as a param

should return

return {
      maxFeePerGas,
      maxPriorityFeePerGas,
    } as EstimateFeesPerGasReturnType<type>   

https://github.com/wagmi-dev/viem/blob/5c95fafceffe7f399b5b5ee32119e2d78a0c8acd/src/actions/public/estimateFeesPerGas.ts#L130-L137

Steps To Reproduce

No response

Link to Minimal Reproducible Example (StackBlitz, CodeSandbox, GitHub repo etc.)

No response

Anything else?

No response

Remove `feeCurrency`, `gatewayFee`, and `gatewayFeeRecipient` properties from transaction receipts

Is there an existing issue for this?

  • I have searched the existing issues

Package Version

1.16.0

Description

I build the following CIP-42 transaction.

Note that I specify cUSD as the fee currency:

const transactionHash = await client.sendTransaction({
        account, // Sender
        to: "0x70997970c51812dc3a010c7d01b50e0d17dc79c8", // Recipient (illustrative address)
        value: parseEther("0.01"), // 0.01 CELO
        feeCurrency: "0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1", // cUSD fee currency
        maxFeePerGas: parseGwei("10"), // Special field for dynamic fee transaction type (EIP-1559)
        maxPriorityFeePerGas: parseGwei("10"), // Special field for dynamic fee transaction type (EIP-1559)
    });

Source: 0xarthurxyz/txtypes

When I parse (and format) the transaction receipt with:

const transactionReceipt = await publicClient.waitForTransactionReceipt({
        hash: await transactionHash,
});

printFormattedTransactionReceipt(transactionReceipt);

The feeCurrency field is undefined.

Transaction details: {
  type: '0x7c',
  status: 'success',
  transactionHash: '0x9935c26499205b028a2518cfa5a32b7ebf68533deec414c8ded9f91ae5aa5dd8',
  from: '0x303c22e6ef01cba9d03259248863836cb91336d5',
  to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',
  feeCurrency: undefined
} 

This is expected, because the feeCurrency, gatewayFee, and gatewayFeeRecipient fields are never included in a transaction receipt. See here where the transaction receipt is defined in the Celo blockchain client.

That means the 3 fields can be removed from the transaction receipt

transactionReceipt: /*#__PURE__*/ defineTransactionReceipt({
    format(
      args: CeloRpcTransactionReceiptOverrides,
    ): CeloTransactionReceiptOverrides {
      return {
-        feeCurrency: args.feeCurrency,
-        gatewayFee: args.gatewayFee ? hexToBigInt(args.gatewayFee) : null,
-        gatewayFeeRecipient: args.gatewayFeeRecipient,
      }
    },
  }),

See Slack discussion with the Blockchain team here.

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.