kandi background
Explore Kits

truffle | Crafted with the finest cacaos | Blockchain library

 by   trufflesuite TypeScript Version: v5.5.11 License: MIT

 by   trufflesuite TypeScript Version: v5.5.11 License: MIT

Download this library from

kandi X-RAY | truffle Summary

truffle is a TypeScript library typically used in Financial Services, Fintech, Blockchain, Ethereum applications. truffle has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can download it from GitHub.
Truffle is a development environment, testing framework and asset pipeline for Ethereum, aiming to make life as an Ethereum developer easier. With Truffle, you get:.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • truffle has a medium active ecosystem.
  • It has 13000 star(s) with 2139 fork(s). There are 347 watchers for this library.
  • There were 5 major release(s) in the last 6 months.
  • There are 465 open issues and 2100 have been closed. On average issues are closed in 273 days. There are 39 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of truffle is v5.5.11
truffle Support
Best in #Blockchain
Average in #Blockchain
truffle Support
Best in #Blockchain
Average in #Blockchain

quality kandi Quality

  • truffle has 0 bugs and 2 code smells.
truffle Quality
Best in #Blockchain
Average in #Blockchain
truffle Quality
Best in #Blockchain
Average in #Blockchain

securitySecurity

  • truffle has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • truffle code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
truffle Security
Best in #Blockchain
Average in #Blockchain
truffle Security
Best in #Blockchain
Average in #Blockchain

license License

  • truffle is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
truffle License
Best in #Blockchain
Average in #Blockchain
truffle License
Best in #Blockchain
Average in #Blockchain

buildReuse

  • truffle releases are available to install and integrate.
  • Installation instructions, examples and code snippets are available.
  • It has 37 lines of code, 2 functions and 940 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
truffle Reuse
Best in #Blockchain
Average in #Blockchain
truffle Reuse
Best in #Blockchain
Average in #Blockchain
Top functions reviewed by kandi - BETA

kandi has reviewed truffle and discovered the below as its top functions. This is intended to give you an instant insight into truffle implemented functionality, and help decide if they suit your requirements.

  • Create the step selector for a step .
  • Set transaction log actions
  • Update code storage .
  • Contract instance
  • Maps the action and updates the new path to the new one .
  • Compiles JSON files into an object that can be written to JSON .
  • recursively process all build contracts
  • Runs provided sources
  • Creates the step selector for the step selector .
  • Process a target

truffle Key Features

Built-in smart contract compilation, linking, deployment and binary management.

Automated contract testing with Mocha and Chai.

Configurable build pipeline with support for custom build processes.

Scriptable deployment & migrations framework.

Network management for deploying to many public & private networks.

Interactive console for direct contract communication.

Instant rebuilding of assets during development.

External script runner that executes scripts within a Truffle environment.

Install

copy iconCopydownload iconDownload
$ npm install -g truffle

Quick Usage

copy iconCopydownload iconDownload
$ truffle init

Development

copy iconCopydownload iconDownload
# Install
npm install -g yarn
yarn bootstrap

# Test
yarn test

# Adding dependencies to a package
cd packages/<truffle-package>
yarn add <npm-package> [--dev] # Use yarn

contract function invoked by web3py without error but have no effect (ganache local network)

copy iconCopydownload iconDownload
assert tx_receipt.status == 1

Getting Error on installing Truffle on windows 10 using npm install truffle -g

copy iconCopydownload iconDownload
npm install -g truffle@5.4.29

PS C:\Windows\system32> npm list -g
C:\Users\*****\AppData\Roaming\npm
+-- ganache-cli@6.12.2
+-- node-gyp@8.2.0
+-- npm@8.0.0
+-- **truffle@5.4.29**
`-- yarn@1.22.17


PS C:\Windows\system32> truffle
Truffle v5.4.29 - a development framework for Ethereum

Usage: truffle <command> [options]

Commands:
  build     Execute build pipeline (if configuration present)
  compile   Compile contract source files
  config    Set user-level configuration options
  console   Run a console with contract abstractions and commands available
  create    Helper to create new contracts, migrations and tests
  db        Database interface commands
  debug     Interactively debug any transaction on the blockchain
  deploy    (alias for migrate)
  develop   Open a console with a local development blockchain
  exec      Execute a JS module within this Truffle environment
  help      List all commands or provide information about a specific command
  init      Initialize new and empty Ethereum project
  install   Install a package from the Ethereum Package Registry
  migrate   Run migrations to deploy contracts
  networks  Show addresses for deployed contracts on each network
  obtain    Fetch and cache a specified compiler
  opcode    Print the compiled opcodes for a given contract
  preserve  Save data to decentralized storage platforms like IPFS and Filecoin
  publish   Publish a package to the Ethereum Package Registry
  run       Run a third-party command
  test      Run JavaScript and Solidity tests
  unbox     Download a Truffle Box, a pre-built Truffle project
  version   Show version number and exit
  watch     Watch filesystem for changes and rebuild the project automatically

See more at http://trufflesuite.com/docs

How do I interact with Uniswap V2 in a Truffle test suite?

copy iconCopydownload iconDownload
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        virtual
        override
        payable
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
        IWETH(WETH).deposit{value: amounts[0]}();
        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
        _swap(amounts, path, to);
    }
uint amountIn = 50 * 10 ** DAI.decimals();
require(DAI.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');
mapping(address=>mapping(address=>uint)) public allowance;
// token address is allowign uniswap address for this much token
const startSwap = async () => {
    await approve()
    await swapToken()
}
const MyContract = artifacts.require("MyContract");
const Dai = artifacts.require("Dai");

// ganache provides an array of accounts
contract("Uniswap", (ganachProvidedAccounts) => { 
  let myContract,dai;
  // intialize the contracts before each test
  before(async () => {
    myContract = await myContract.new();
    dai = await Dai.new();
  })

  describe("Swapping", async () => {
    it("swap tokens", async () => {
      let result;
     
      // first ask for approval of 100 token transfer
      await dai.approve(myContract.address, tokens("100"), {
        from:ganachProvidedAccounts[0] ,
      });
      // // check staking for customer
      await myContract.swapExactETHForTokens("100"), { from: ganachProvidedAccounts[0] });
      // make your assetion
})})
-----------------------
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        virtual
        override
        payable
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
        IWETH(WETH).deposit{value: amounts[0]}();
        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
        _swap(amounts, path, to);
    }
uint amountIn = 50 * 10 ** DAI.decimals();
require(DAI.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');
mapping(address=>mapping(address=>uint)) public allowance;
// token address is allowign uniswap address for this much token
const startSwap = async () => {
    await approve()
    await swapToken()
}
const MyContract = artifacts.require("MyContract");
const Dai = artifacts.require("Dai");

// ganache provides an array of accounts
contract("Uniswap", (ganachProvidedAccounts) => { 
  let myContract,dai;
  // intialize the contracts before each test
  before(async () => {
    myContract = await myContract.new();
    dai = await Dai.new();
  })

  describe("Swapping", async () => {
    it("swap tokens", async () => {
      let result;
     
      // first ask for approval of 100 token transfer
      await dai.approve(myContract.address, tokens("100"), {
        from:ganachProvidedAccounts[0] ,
      });
      // // check staking for customer
      await myContract.swapExactETHForTokens("100"), { from: ganachProvidedAccounts[0] });
      // make your assetion
})})
-----------------------
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        virtual
        override
        payable
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
        IWETH(WETH).deposit{value: amounts[0]}();
        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
        _swap(amounts, path, to);
    }
uint amountIn = 50 * 10 ** DAI.decimals();
require(DAI.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');
mapping(address=>mapping(address=>uint)) public allowance;
// token address is allowign uniswap address for this much token
const startSwap = async () => {
    await approve()
    await swapToken()
}
const MyContract = artifacts.require("MyContract");
const Dai = artifacts.require("Dai");

// ganache provides an array of accounts
contract("Uniswap", (ganachProvidedAccounts) => { 
  let myContract,dai;
  // intialize the contracts before each test
  before(async () => {
    myContract = await myContract.new();
    dai = await Dai.new();
  })

  describe("Swapping", async () => {
    it("swap tokens", async () => {
      let result;
     
      // first ask for approval of 100 token transfer
      await dai.approve(myContract.address, tokens("100"), {
        from:ganachProvidedAccounts[0] ,
      });
      // // check staking for customer
      await myContract.swapExactETHForTokens("100"), { from: ganachProvidedAccounts[0] });
      // make your assetion
})})
-----------------------
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        virtual
        override
        payable
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
        IWETH(WETH).deposit{value: amounts[0]}();
        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
        _swap(amounts, path, to);
    }
uint amountIn = 50 * 10 ** DAI.decimals();
require(DAI.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');
mapping(address=>mapping(address=>uint)) public allowance;
// token address is allowign uniswap address for this much token
const startSwap = async () => {
    await approve()
    await swapToken()
}
const MyContract = artifacts.require("MyContract");
const Dai = artifacts.require("Dai");

// ganache provides an array of accounts
contract("Uniswap", (ganachProvidedAccounts) => { 
  let myContract,dai;
  // intialize the contracts before each test
  before(async () => {
    myContract = await myContract.new();
    dai = await Dai.new();
  })

  describe("Swapping", async () => {
    it("swap tokens", async () => {
      let result;
     
      // first ask for approval of 100 token transfer
      await dai.approve(myContract.address, tokens("100"), {
        from:ganachProvidedAccounts[0] ,
      });
      // // check staking for customer
      await myContract.swapExactETHForTokens("100"), { from: ganachProvidedAccounts[0] });
      // make your assetion
})})
-----------------------
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        virtual
        override
        payable
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
        IWETH(WETH).deposit{value: amounts[0]}();
        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
        _swap(amounts, path, to);
    }
uint amountIn = 50 * 10 ** DAI.decimals();
require(DAI.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.');
mapping(address=>mapping(address=>uint)) public allowance;
// token address is allowign uniswap address for this much token
const startSwap = async () => {
    await approve()
    await swapToken()
}
const MyContract = artifacts.require("MyContract");
const Dai = artifacts.require("Dai");

// ganache provides an array of accounts
contract("Uniswap", (ganachProvidedAccounts) => { 
  let myContract,dai;
  // intialize the contracts before each test
  before(async () => {
    myContract = await myContract.new();
    dai = await Dai.new();
  })

  describe("Swapping", async () => {
    it("swap tokens", async () => {
      let result;
     
      // first ask for approval of 100 token transfer
      await dai.approve(myContract.address, tokens("100"), {
        from:ganachProvidedAccounts[0] ,
      });
      // // check staking for customer
      await myContract.swapExactETHForTokens("100"), { from: ganachProvidedAccounts[0] });
      // make your assetion
})})
-----------------------
INFURA_API_KEY=A45..
MY_ACCOUNT=0x...
ganache-cli --fork https://ropsten.infura.io/v3/$INFURA_API_KEY \ --unlock $MY_ACCOUNT \ --networkId 999
truffle console --network ropsten_fork
-----------------------
INFURA_API_KEY=A45..
MY_ACCOUNT=0x...
ganache-cli --fork https://ropsten.infura.io/v3/$INFURA_API_KEY \ --unlock $MY_ACCOUNT \ --networkId 999
truffle console --network ropsten_fork

Deploying Uniswap v2 / Sushiswap or similar in Brownie, Hardhat or Truffle test suite

copy iconCopydownload iconDownload
npx hardhat node
var provider = new ethers.providers.WebSocketProvider("ws://localhost:8545");
var signer = provider.getSigner();
const compiledUniswapFactory = require("@uniswap/v2-core/build/UniswapV2Factory.json");
var uniswapFactory = await new ethers.ContractFactory(compiledUniswapFactory.interface,compiledUniswapFactory.bytecode,signer).deploy(await signer.getAddress());
const compiledWETH = require("canonical-weth/build/conrtacts/WETH.json";
var WETH = await new ethers.ContractFactory(WETH.interface,WETH.bytecode,signer).deploy();
const compiledUniswapRouter = require("@uniswap/v2-periphery/build/UniswapV2Router02");
var router = await new ethers.ContractFactory(compiledUniswapRouter.abi,compiledUniswapRouter.bytecode,signer).deploy(uniswapFactory.address,WETH.address);
const compiledERC20 = require("../../../Ethereum/Ethereum/sources/ERC20.sol/Token.json");
var erc20Factory = new ethers.ContractFactory(compiledERC20.abi,compiledERC20.bytecode,signer);

var erc20_0 = await erc20Factory.deploy("1000000", "Token 0", "5", "T0");
var erc20_1 = await erc20Factory.deploy("1000000", "Token 1", "5", "T1");
uniswapFactory.createPair(erc20_0.address,erc20_1.address);
-----------------------
npx hardhat node
var provider = new ethers.providers.WebSocketProvider("ws://localhost:8545");
var signer = provider.getSigner();
const compiledUniswapFactory = require("@uniswap/v2-core/build/UniswapV2Factory.json");
var uniswapFactory = await new ethers.ContractFactory(compiledUniswapFactory.interface,compiledUniswapFactory.bytecode,signer).deploy(await signer.getAddress());
const compiledWETH = require("canonical-weth/build/conrtacts/WETH.json";
var WETH = await new ethers.ContractFactory(WETH.interface,WETH.bytecode,signer).deploy();
const compiledUniswapRouter = require("@uniswap/v2-periphery/build/UniswapV2Router02");
var router = await new ethers.ContractFactory(compiledUniswapRouter.abi,compiledUniswapRouter.bytecode,signer).deploy(uniswapFactory.address,WETH.address);
const compiledERC20 = require("../../../Ethereum/Ethereum/sources/ERC20.sol/Token.json");
var erc20Factory = new ethers.ContractFactory(compiledERC20.abi,compiledERC20.bytecode,signer);

var erc20_0 = await erc20Factory.deploy("1000000", "Token 0", "5", "T0");
var erc20_1 = await erc20Factory.deploy("1000000", "Token 1", "5", "T1");
uniswapFactory.createPair(erc20_0.address,erc20_1.address);
-----------------------
npx hardhat node
var provider = new ethers.providers.WebSocketProvider("ws://localhost:8545");
var signer = provider.getSigner();
const compiledUniswapFactory = require("@uniswap/v2-core/build/UniswapV2Factory.json");
var uniswapFactory = await new ethers.ContractFactory(compiledUniswapFactory.interface,compiledUniswapFactory.bytecode,signer).deploy(await signer.getAddress());
const compiledWETH = require("canonical-weth/build/conrtacts/WETH.json";
var WETH = await new ethers.ContractFactory(WETH.interface,WETH.bytecode,signer).deploy();
const compiledUniswapRouter = require("@uniswap/v2-periphery/build/UniswapV2Router02");
var router = await new ethers.ContractFactory(compiledUniswapRouter.abi,compiledUniswapRouter.bytecode,signer).deploy(uniswapFactory.address,WETH.address);
const compiledERC20 = require("../../../Ethereum/Ethereum/sources/ERC20.sol/Token.json");
var erc20Factory = new ethers.ContractFactory(compiledERC20.abi,compiledERC20.bytecode,signer);

var erc20_0 = await erc20Factory.deploy("1000000", "Token 0", "5", "T0");
var erc20_1 = await erc20Factory.deploy("1000000", "Token 1", "5", "T1");
uniswapFactory.createPair(erc20_0.address,erc20_1.address);
-----------------------
npx hardhat node
var provider = new ethers.providers.WebSocketProvider("ws://localhost:8545");
var signer = provider.getSigner();
const compiledUniswapFactory = require("@uniswap/v2-core/build/UniswapV2Factory.json");
var uniswapFactory = await new ethers.ContractFactory(compiledUniswapFactory.interface,compiledUniswapFactory.bytecode,signer).deploy(await signer.getAddress());
const compiledWETH = require("canonical-weth/build/conrtacts/WETH.json";
var WETH = await new ethers.ContractFactory(WETH.interface,WETH.bytecode,signer).deploy();
const compiledUniswapRouter = require("@uniswap/v2-periphery/build/UniswapV2Router02");
var router = await new ethers.ContractFactory(compiledUniswapRouter.abi,compiledUniswapRouter.bytecode,signer).deploy(uniswapFactory.address,WETH.address);
const compiledERC20 = require("../../../Ethereum/Ethereum/sources/ERC20.sol/Token.json");
var erc20Factory = new ethers.ContractFactory(compiledERC20.abi,compiledERC20.bytecode,signer);

var erc20_0 = await erc20Factory.deploy("1000000", "Token 0", "5", "T0");
var erc20_1 = await erc20Factory.deploy("1000000", "Token 1", "5", "T1");
uniswapFactory.createPair(erc20_0.address,erc20_1.address);
-----------------------
npx hardhat node
var provider = new ethers.providers.WebSocketProvider("ws://localhost:8545");
var signer = provider.getSigner();
const compiledUniswapFactory = require("@uniswap/v2-core/build/UniswapV2Factory.json");
var uniswapFactory = await new ethers.ContractFactory(compiledUniswapFactory.interface,compiledUniswapFactory.bytecode,signer).deploy(await signer.getAddress());
const compiledWETH = require("canonical-weth/build/conrtacts/WETH.json";
var WETH = await new ethers.ContractFactory(WETH.interface,WETH.bytecode,signer).deploy();
const compiledUniswapRouter = require("@uniswap/v2-periphery/build/UniswapV2Router02");
var router = await new ethers.ContractFactory(compiledUniswapRouter.abi,compiledUniswapRouter.bytecode,signer).deploy(uniswapFactory.address,WETH.address);
const compiledERC20 = require("../../../Ethereum/Ethereum/sources/ERC20.sol/Token.json");
var erc20Factory = new ethers.ContractFactory(compiledERC20.abi,compiledERC20.bytecode,signer);

var erc20_0 = await erc20Factory.deploy("1000000", "Token 0", "5", "T0");
var erc20_1 = await erc20Factory.deploy("1000000", "Token 1", "5", "T1");
uniswapFactory.createPair(erc20_0.address,erc20_1.address);
-----------------------
npx hardhat node
var provider = new ethers.providers.WebSocketProvider("ws://localhost:8545");
var signer = provider.getSigner();
const compiledUniswapFactory = require("@uniswap/v2-core/build/UniswapV2Factory.json");
var uniswapFactory = await new ethers.ContractFactory(compiledUniswapFactory.interface,compiledUniswapFactory.bytecode,signer).deploy(await signer.getAddress());
const compiledWETH = require("canonical-weth/build/conrtacts/WETH.json";
var WETH = await new ethers.ContractFactory(WETH.interface,WETH.bytecode,signer).deploy();
const compiledUniswapRouter = require("@uniswap/v2-periphery/build/UniswapV2Router02");
var router = await new ethers.ContractFactory(compiledUniswapRouter.abi,compiledUniswapRouter.bytecode,signer).deploy(uniswapFactory.address,WETH.address);
const compiledERC20 = require("../../../Ethereum/Ethereum/sources/ERC20.sol/Token.json");
var erc20Factory = new ethers.ContractFactory(compiledERC20.abi,compiledERC20.bytecode,signer);

var erc20_0 = await erc20Factory.deploy("1000000", "Token 0", "5", "T0");
var erc20_1 = await erc20Factory.deploy("1000000", "Token 1", "5", "T1");
uniswapFactory.createPair(erc20_0.address,erc20_1.address);
-----------------------
npx hardhat node
var provider = new ethers.providers.WebSocketProvider("ws://localhost:8545");
var signer = provider.getSigner();
const compiledUniswapFactory = require("@uniswap/v2-core/build/UniswapV2Factory.json");
var uniswapFactory = await new ethers.ContractFactory(compiledUniswapFactory.interface,compiledUniswapFactory.bytecode,signer).deploy(await signer.getAddress());
const compiledWETH = require("canonical-weth/build/conrtacts/WETH.json";
var WETH = await new ethers.ContractFactory(WETH.interface,WETH.bytecode,signer).deploy();
const compiledUniswapRouter = require("@uniswap/v2-periphery/build/UniswapV2Router02");
var router = await new ethers.ContractFactory(compiledUniswapRouter.abi,compiledUniswapRouter.bytecode,signer).deploy(uniswapFactory.address,WETH.address);
const compiledERC20 = require("../../../Ethereum/Ethereum/sources/ERC20.sol/Token.json");
var erc20Factory = new ethers.ContractFactory(compiledERC20.abi,compiledERC20.bytecode,signer);

var erc20_0 = await erc20Factory.deploy("1000000", "Token 0", "5", "T0");
var erc20_1 = await erc20Factory.deploy("1000000", "Token 1", "5", "T1");
uniswapFactory.createPair(erc20_0.address,erc20_1.address);
-----------------------
pragma solidity ^0.6.6;

interface IUniswap {
  function swapExactETHForTokens(
    uint amountOutMin,
    address[] calldata path,
    address to,
    uint deadline)
  external
  payable
  returns (uint[] memory amounts);
  function WETH() external pure returns (address);
}

contract UniswapTradeExample {
  IUniswap uniswap;
  
  // Pass in address of UniswapV2Router02
  constructor(address _uniswap) public {
    uniswap = IUniswap(_uniswap);
  }

  function swapExactETHForTokens(uint amountOutMin, address token) external payable {
    address[] memory path = new address[](2);
    path[0] = uniswap.WETH();
    path[1] = token;
    uniswap.swapExactETHForTokens{value: msg.value}(
      amountOutMin, 
      path,
      msg.sender,
      now
    );
  }
}
networks: {
  hardhat: {
    forking: {
      url: "https://eth-mainnet.alchemyapi.io/v2/<key>",
      blockNumber: 14189520
    }
  }
}
const { assert } = require("chai");
const { ethers } = require("hardhat");
const ERC20ABI = require('./ERC20.json');

const UNISWAPV2ROUTER02_ADDRESS = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D";
const DAI_ADDRESS = "0x6b175474e89094c44da98b954eedeac495271d0f";

describe("UniswapTradeExample", function () {
    it("Swap ETH for DAI", async function () {
        const provider = ethers.provider;
        const [owner, addr1] = await ethers.getSigners();
        const DAI = new ethers.Contract(DAI_ADDRESS, ERC20ABI, provider);

        // Assert addr1 has 1000 ETH to start
        addr1Balance = await provider.getBalance(addr1.address);
        expectedBalance = ethers.BigNumber.from("10000000000000000000000");
        assert(addr1Balance.eq(expectedBalance));

        // Assert addr1 DAI balance is 0
        addr1Dai = await DAI.balanceOf(addr1.address);
        assert(addr1Dai.isZero());

        // Deploy UniswapTradeExample
        const uniswapTradeExample =
            await ethers.getContractFactory("UniswapTradeExample")
                .then(contract => contract.deploy(UNISWAPV2ROUTER02_ADDRESS));
        await uniswapTradeExample.deployed();

        // Swap 1 ETH for DAI
        await uniswapTradeExample.connect(addr1).swapExactETHForTokens(
            0,
            DAI_ADDRESS,
            { value: ethers.utils.parseEther("1") }
        );

        // Assert addr1Balance contains one less ETH
        expectedBalance = addr1Balance.sub(ethers.utils.parseEther("1"));
        addr1Balance = await provider.getBalance(addr1.address);
        assert(addr1Balance.lt(expectedBalance));

        // Assert DAI balance increased
        addr1Dai = await DAI.balanceOf(addr1.address);
        assert(addr1Dai.gt(ethers.BigNumber.from("0")));
    });
});
-----------------------
pragma solidity ^0.6.6;

interface IUniswap {
  function swapExactETHForTokens(
    uint amountOutMin,
    address[] calldata path,
    address to,
    uint deadline)
  external
  payable
  returns (uint[] memory amounts);
  function WETH() external pure returns (address);
}

contract UniswapTradeExample {
  IUniswap uniswap;
  
  // Pass in address of UniswapV2Router02
  constructor(address _uniswap) public {
    uniswap = IUniswap(_uniswap);
  }

  function swapExactETHForTokens(uint amountOutMin, address token) external payable {
    address[] memory path = new address[](2);
    path[0] = uniswap.WETH();
    path[1] = token;
    uniswap.swapExactETHForTokens{value: msg.value}(
      amountOutMin, 
      path,
      msg.sender,
      now
    );
  }
}
networks: {
  hardhat: {
    forking: {
      url: "https://eth-mainnet.alchemyapi.io/v2/<key>",
      blockNumber: 14189520
    }
  }
}
const { assert } = require("chai");
const { ethers } = require("hardhat");
const ERC20ABI = require('./ERC20.json');

const UNISWAPV2ROUTER02_ADDRESS = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D";
const DAI_ADDRESS = "0x6b175474e89094c44da98b954eedeac495271d0f";

describe("UniswapTradeExample", function () {
    it("Swap ETH for DAI", async function () {
        const provider = ethers.provider;
        const [owner, addr1] = await ethers.getSigners();
        const DAI = new ethers.Contract(DAI_ADDRESS, ERC20ABI, provider);

        // Assert addr1 has 1000 ETH to start
        addr1Balance = await provider.getBalance(addr1.address);
        expectedBalance = ethers.BigNumber.from("10000000000000000000000");
        assert(addr1Balance.eq(expectedBalance));

        // Assert addr1 DAI balance is 0
        addr1Dai = await DAI.balanceOf(addr1.address);
        assert(addr1Dai.isZero());

        // Deploy UniswapTradeExample
        const uniswapTradeExample =
            await ethers.getContractFactory("UniswapTradeExample")
                .then(contract => contract.deploy(UNISWAPV2ROUTER02_ADDRESS));
        await uniswapTradeExample.deployed();

        // Swap 1 ETH for DAI
        await uniswapTradeExample.connect(addr1).swapExactETHForTokens(
            0,
            DAI_ADDRESS,
            { value: ethers.utils.parseEther("1") }
        );

        // Assert addr1Balance contains one less ETH
        expectedBalance = addr1Balance.sub(ethers.utils.parseEther("1"));
        addr1Balance = await provider.getBalance(addr1.address);
        assert(addr1Balance.lt(expectedBalance));

        // Assert DAI balance increased
        addr1Dai = await DAI.balanceOf(addr1.address);
        assert(addr1Dai.gt(ethers.BigNumber.from("0")));
    });
});
-----------------------
pragma solidity ^0.6.6;

interface IUniswap {
  function swapExactETHForTokens(
    uint amountOutMin,
    address[] calldata path,
    address to,
    uint deadline)
  external
  payable
  returns (uint[] memory amounts);
  function WETH() external pure returns (address);
}

contract UniswapTradeExample {
  IUniswap uniswap;
  
  // Pass in address of UniswapV2Router02
  constructor(address _uniswap) public {
    uniswap = IUniswap(_uniswap);
  }

  function swapExactETHForTokens(uint amountOutMin, address token) external payable {
    address[] memory path = new address[](2);
    path[0] = uniswap.WETH();
    path[1] = token;
    uniswap.swapExactETHForTokens{value: msg.value}(
      amountOutMin, 
      path,
      msg.sender,
      now
    );
  }
}
networks: {
  hardhat: {
    forking: {
      url: "https://eth-mainnet.alchemyapi.io/v2/<key>",
      blockNumber: 14189520
    }
  }
}
const { assert } = require("chai");
const { ethers } = require("hardhat");
const ERC20ABI = require('./ERC20.json');

const UNISWAPV2ROUTER02_ADDRESS = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D";
const DAI_ADDRESS = "0x6b175474e89094c44da98b954eedeac495271d0f";

describe("UniswapTradeExample", function () {
    it("Swap ETH for DAI", async function () {
        const provider = ethers.provider;
        const [owner, addr1] = await ethers.getSigners();
        const DAI = new ethers.Contract(DAI_ADDRESS, ERC20ABI, provider);

        // Assert addr1 has 1000 ETH to start
        addr1Balance = await provider.getBalance(addr1.address);
        expectedBalance = ethers.BigNumber.from("10000000000000000000000");
        assert(addr1Balance.eq(expectedBalance));

        // Assert addr1 DAI balance is 0
        addr1Dai = await DAI.balanceOf(addr1.address);
        assert(addr1Dai.isZero());

        // Deploy UniswapTradeExample
        const uniswapTradeExample =
            await ethers.getContractFactory("UniswapTradeExample")
                .then(contract => contract.deploy(UNISWAPV2ROUTER02_ADDRESS));
        await uniswapTradeExample.deployed();

        // Swap 1 ETH for DAI
        await uniswapTradeExample.connect(addr1).swapExactETHForTokens(
            0,
            DAI_ADDRESS,
            { value: ethers.utils.parseEther("1") }
        );

        // Assert addr1Balance contains one less ETH
        expectedBalance = addr1Balance.sub(ethers.utils.parseEther("1"));
        addr1Balance = await provider.getBalance(addr1.address);
        assert(addr1Balance.lt(expectedBalance));

        // Assert DAI balance increased
        addr1Dai = await DAI.balanceOf(addr1.address);
        assert(addr1Dai.gt(ethers.BigNumber.from("0")));
    });
});

Truffle installation error: &quot;install latest visual studio version&quot;

copy iconCopydownload iconDownload
npm install -g npm@7.24.2

R: dpois not returning correct probabilities?

copy iconCopydownload iconDownload
trufflesFound<-c(rep(0,203),rep(1,39),rep(2,18),rep(3,28))
expTruffPois<-dpois(x = 0:3, lambda = mean(trufflesFound)) 
expTruffPois
#> [1] 0.57574908 0.31786147 0.08774301 0.01614715
sum(expTruffPois)
#> [1] 0.9975007

How can get json interface of the smart contract

copy iconCopydownload iconDownload
var output = JSON.parse(solc.compile(JSON.stringify(input))); // an object
// it spits out bytecode and interface


module.exports = output.contracts["Lottery.sol"]["Lottery"];
    const { abi, evm } = require("./compile");
-----------------------
var output = JSON.parse(solc.compile(JSON.stringify(input))); // an object
// it spits out bytecode and interface


module.exports = output.contracts["Lottery.sol"]["Lottery"];
    const { abi, evm } = require("./compile");
-----------------------
const path = require("path");
const fs = require("fs");
const solc = require("solc");

const inboxPath = path.resolve(__dirname, "contracts", "Example.sol");
const source = fs.readFileSync(inboxPath, "utf8");

const input = {
  language: "Solidity",
  sources: {
    "Example.sol": {
      content: source,
    },
  },
  settings: {
    outputSelection: {
      "*": {
        "*": ["*"],
      },
    },
  },
};

const output = JSON.parse(solc.compile(JSON.stringify(input)));

module.exports = output.contracts["Example.sol"]["Example"];
const assert = require("assert");
const ganache = require("ganache-cli");
const Web3 = require("web3");
const web3 = new Web3(ganache.provider());
const { abi, evm } = require("../compile");

let accounts;
let exampleContract;
beforeEach(async () => {
  // Get a list of all accounts
  accounts = await web3.eth.getAccounts();

  // Use one of those accounts to deploy the contract
  exampleContract = await new web3.eth
    .Contract(abi)
    .deploy({
      data: evm.bytecode.object,
      arguments: ["Hi there"],
    })
    .send({ from: accounts[0], gas: 1000000 });
});

describe("Example", () => {
  it("deploys a contract", () => {
    console.log(exampleContract);
  });
});
-----------------------
const path = require("path");
const fs = require("fs");
const solc = require("solc");

const inboxPath = path.resolve(__dirname, "contracts", "Example.sol");
const source = fs.readFileSync(inboxPath, "utf8");

const input = {
  language: "Solidity",
  sources: {
    "Example.sol": {
      content: source,
    },
  },
  settings: {
    outputSelection: {
      "*": {
        "*": ["*"],
      },
    },
  },
};

const output = JSON.parse(solc.compile(JSON.stringify(input)));

module.exports = output.contracts["Example.sol"]["Example"];
const assert = require("assert");
const ganache = require("ganache-cli");
const Web3 = require("web3");
const web3 = new Web3(ganache.provider());
const { abi, evm } = require("../compile");

let accounts;
let exampleContract;
beforeEach(async () => {
  // Get a list of all accounts
  accounts = await web3.eth.getAccounts();

  // Use one of those accounts to deploy the contract
  exampleContract = await new web3.eth
    .Contract(abi)
    .deploy({
      data: evm.bytecode.object,
      arguments: ["Hi there"],
    })
    .send({ from: accounts[0], gas: 1000000 });
});

describe("Example", () => {
  it("deploys a contract", () => {
    console.log(exampleContract);
  });
});

&quot;revert ERC20: transfer amount exceeds allowance&quot; error when transferring from a smart contract

copy iconCopydownload iconDownload
await token.approve(manager.address, 100000, { from: accounts[1] });
rdk.transferFrom(address(this), msg.sender, howMany); 
// transfer `howMany` of `rdk` tokens
// from the `Manager` address
// to the user invoking the `claimRewards()` function

rdk.transfer(msg.sender, howMany); 
-----------------------
await token.approve(manager.address, 100000, { from: accounts[1] });
rdk.transferFrom(address(this), msg.sender, howMany); 
// transfer `howMany` of `rdk` tokens
// from the `Manager` address
// to the user invoking the `claimRewards()` function

rdk.transfer(msg.sender, howMany); 
-----------------------
await token.approve(manager.address, 100000, { from: accounts[1] });
rdk.transferFrom(address(this), msg.sender, howMany); 
// transfer `howMany` of `rdk` tokens
// from the `Manager` address
// to the user invoking the `claimRewards()` function

rdk.transfer(msg.sender, howMany); 

Is it possible to call a ERC20 function inside a ERC721 contract?

copy iconCopydownload iconDownload
// Inside the nfts contract
ERC20 token = ERC20("your token address here");
token.transferFrom("args");
-----------------------
// Inside the nfts contract
ERC20 token = ERC20("your token address here");
token.transferFrom("args");
-----------------------
import "../interfaces/IERC20.sol";
function stakeTokens(uint256 _amount,address _token) public{
    // add require staments
    // IERC20(_token) this will initialize the contract
    IERC20(_token).transferFrom(msg.sender,address(this),_amount);
 }
-----------------------
import "../interfaces/IERC20.sol";
function stakeTokens(uint256 _amount,address _token) public{
    // add require staments
    // IERC20(_token) this will initialize the contract
    IERC20(_token).transferFrom(msg.sender,address(this),_amount);
 }

Truffle doesn't compile but remix does

copy iconCopydownload iconDownload
 (bool success, bytes memory data) = payable(_to).call{value: _amount}("");
compilers: {
    solc: {
     // adjus tthis based on contract's solidity version
      version: "0.8.4",
    }
  }
pragma solidity >=0.4.22 <0.9.0;
-----------------------
 (bool success, bytes memory data) = payable(_to).call{value: _amount}("");
compilers: {
    solc: {
     // adjus tthis based on contract's solidity version
      version: "0.8.4",
    }
  }
pragma solidity >=0.4.22 <0.9.0;
-----------------------
 (bool success, bytes memory data) = payable(_to).call{value: _amount}("");
compilers: {
    solc: {
     // adjus tthis based on contract's solidity version
      version: "0.8.4",
    }
  }
pragma solidity >=0.4.22 <0.9.0;

Community Discussions

Trending Discussions on truffle
  • contract function invoked by web3py without error but have no effect (ganache local network)
  • Contract &quot;Coin&quot; should be marked as abstract
  • Getting Error on installing Truffle on windows 10 using npm install truffle -g
  • How do I interact with Uniswap V2 in a Truffle test suite?
  • Truffle migrate --network bsc error: header not found
  • Error while installing truffle using &quot;npm i truffle -g&quot;
  • Deploying Uniswap v2 / Sushiswap or similar in Brownie, Hardhat or Truffle test suite
  • Truffle installation error: &quot;install latest visual studio version&quot;
  • R: dpois not returning correct probabilities?
  • How can get json interface of the smart contract
Trending Discussions on truffle

QUESTION

contract function invoked by web3py without error but have no effect (ganache local network)

Asked 2022-Apr-08 at 08:47

compiled code by py-solc-x, then deployed it to the ganache local network using web3py api. first, call a get_balance function and it return as expected. second, call the transfer function and it return without error, but the balance have not changed when I call get_balance later. try to call transfer by sending a raw transaction but it still no effect...

metacoin.sol (provided by truffle doc)

pragma solidity ^0.8.0;

contract MetaCoin {

    mapping (address => uint) balances;

    event Transfer(address indexed _from, address indexed _to, uint _value);    

    constructor() public {
        balances[msg.sender] = 10000;
    }

    function transfer(address receiver, uint amount) public returns(bool sufficient) {
        if (balances[msg.sender] >= amount)
            return false;

        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        emit Transfer(msg.sender, receiver, amount);   
        return true;
    }

    function get_balance(address account) public view returns(uint) {
        return balances[account];
    }
}

interacting.py

    # deploy contract by w3.eth.accounts[0]
    # the balance of the accounts[0] is 10000 (call get_balance() return 10000)
    # then transfer 1000 from accounts[0] to accounts[1]

    deployed_address = '0x538574C591F6e01E22eFa951153a29e6Fc505735'
    contract = w3.eth.contract(address=HexBytes(deployed_address), abi=abi)
    tx_hash = contract.functions.transfer(w3.eth.accounts[1], 1000).transact()
    tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
    print(tx_receipt.contractAddress)

    balance = contract.functions.get_balance(w3.eth.accounts[0]).call()
    print(balance)    
    # still 10000, expect 9000.

the transfer transaction looks good. both gas/gasPrice and dynamic fee transaction have been tried but the balance still the same. it's the problem from the ganache local network setting ? or some required configured steps I missed.

ANSWER

Answered 2022-Apr-08 at 08:47

Check that the transaction went through

assert tx_receipt.status == 1

Also if Ganache does not work then try Ethereum Tester based tests. Example token tests here.

Source https://stackoverflow.com/questions/71794128

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install truffle

You can download it from GitHub.

Support

Please see the Official Truffle Documentation for guides, tips, and examples.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.