ethers#utils TypeScript Examples

The following examples show how to use ethers#utils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: sniper.ts    From pool-sniper with The Unlicense 6 votes vote down vote up
/**
   * Updates token and purchase details + sets up RPC
   * @param {string} tokenAddress of token to purchase
   * @param {string} factoryAddress of Uniswap V2 Factory
   * @param {string} rpcEndpoint for network
   * @param {string} privateKey of purchasing wallet
   * @param {string} purchaseAmount to swap with (input)
   * @param {string} gasPrice to pay
   * @param {number} slippage for trade execution
   * @param {boolean} testnet true if testnet
   */
  constructor(
    tokenAddress: string,
    factoryAddress: string,
    rpcEndpoint: string,
    privateKey: string,
    purchaseAmount: string,
    gasPrice: string,
    slippage: number,
    testnet: boolean
  ) {
    // Setup networking + wallet
    this.rpc = new providers.JsonRpcProvider(rpcEndpoint);
    this.wallet = new Wallet(privateKey, this.rpc);

    // Setup token details
    this.tokenAddress = utils.getAddress(tokenAddress); // Normalize address
    this.factory = new Contract(factoryAddress, ABI_UniswapV2Factory, this.rpc);
    this.purchaseAmount = purchaseAmount;
    this.gasPrice = utils.parseUnits(gasPrice, "gwei");
    this.slippage = slippage;
    this.testnet = testnet;
  }
Example #2
Source File: utilities.ts    From apeswap-swap-core with GNU General Public License v3.0 6 votes vote down vote up
{ getAddress, keccak256, defaultAbiCoder, toUtf8Bytes, solidityPack } = utils
Example #3
Source File: useDecodedCall.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
decodeCallUsingEthersInterface = (
  call: Call,
  contractInterface: utils.Interface,
  callType?: SupportedAction
): DecodedCall => {
  // Get the first 10 characters of Tx data, which is the Function Selector (SigHash).
  const sigHash = call.data.substring(0, 10);

  // Find the ABI function fragment for the sighash.
  const functionFragment = contractInterface.getFunction(sigHash);
  if (!functionFragment) return null;

  // Decode the function parameters.
  const params = contractInterface.decodeFunctionData(
    functionFragment,
    call.data
  );

  const paramsJson = functionFragment.inputs.reduce((acc, input) => {
    acc[input.name] = params[input.name];
    return acc;
  }, {} as Record<string, any>);

  return {
    callType: callType || SupportedAction.GENERIC_CALL,
    from: call.from,
    to: call.to,
    value: call.value,
    function: functionFragment,
    args: paramsJson,
  };
}
Example #4
Source File: Encoding.ts    From compound-protocol with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export function toEncodableNum(amountArgRaw: string | encodedNumber): encodedNumber {
  let bigNumber;
  if (amountArgRaw instanceof BigNumber) {
    bigNumber = amountArgRaw;
  } else {
    bigNumber = new BigNumber(amountArgRaw.toString());
  }

  if (bigNumber.lt(smallEnoughNumber)) {
    // The Ethers abi encoder can handle regular numbers (including with fractional part)
    // and its own internal big number class which is different from BigNumber.js published on npm (and can't accept
    // fractional parts.)
    // If the input is not huge, we just use a number, otherwise we try to use the Ethers class.

    return Number(amountArgRaw);
  } else {
    // bigNumberify (and the result class) only accept integers as digits, so we do .toFixed() to convert, for example, 1e4 to 10000.
    // Rather than doing toFixed(0) and silently truncating a fractional part, we'll let it through and get an error.
    // that case
    return utils.bigNumberify(bigNumber.toFixed());
  }
}
Example #5
Source File: libraryUtils.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
// Converts a fully qualified contract name in a bytecode link id.
// (A fully qualified name looks like: `contracts/mocks/LibraryMock.sol:LibraryMock`)
export function convertLibraryNameToLinkId(libraryName: string): string {
  if (!(libraryName.includes(path.sep) && libraryName.includes(":"))) {
    throw new Error(
      "Converting library name to link id requires a fully qualified " +
      "contract name. Example: `contracts/mocks/LibraryMock.sol:LibraryMock`"
    );
  }

  const hashedName = utils.keccak256(utils.toUtf8Bytes(libraryName));
  return `__$${hashedName.slice(2).slice(0, 34)}$__`;
}
Example #6
Source File: notification.ts    From panvala with Apache License 2.0 6 votes vote down vote up
/**
 * Get all notifications for a user's address
 */
export function getByAddress(req, res) {
  const { address } = req.params;

  try {
    const validatedAddress = utils.getAddress(address.toLowerCase());

    return getNotificationsByAddress(validatedAddress)
      .then(notifications => {
        return res.json(notifications);
      })
      .catch(error => {
        const msg = `Error while attempting to get events: ${error}`;
        console.error(msg);
        return res.status(400).send(msg);
      });
  } catch (error) {
    const msg = `Invalid address provided in body: ${error}`;
    console.error(msg);
    return res.status(400).send(msg);
  }
}
Example #7
Source File: zapin-fetch-data.ts    From rugenerous-frontend with MIT License 6 votes vote down vote up
zapinLpData = async (
  bond: IAllBondData,
  token: IToken,
  tokenAmmount: string,
  network: Networks,
  slippage: number,
) => {
  const addresses = getAddresses(network);

  const sellToken = token.isAvax ? ethers.constants.AddressZero : token.address;
  const buyToken = bond.getAddressForReserve(network);

  const url = `https://api.zapper.fi/v1/zap-in/pool/traderjoe/transaction?gasPrice=1000000000000&ownerAddress=${addresses.ZAPIN_ADDRESS}&sellAmount=${tokenAmmount}&sellTokenAddress=${sellToken}&poolAddress=${buyToken}&slippagePercentage=${slippage}&network=avalanche&api_key=96e0cc51-a62e-42ca-acee-910ea7d2a241&skipGasEstimate=true`;

  const { data } = await axios.get(url);

  const zapinInterface = new utils.Interface(TraderZapinContract);

  const { _swapTarget, swapData } = zapinInterface.decodeFunctionData("ZapIn", data.data);

  return [_swapTarget, swapData, data.minTokens];
}
Example #8
Source File: address.ts    From useDApp with MIT License 6 votes vote down vote up
/**
 * @public
 */
export function shortenAddress(address: string): string {
  try {
    const formattedAddress = utils.getAddress(address)
    return shortenString(formattedAddress)
  } catch {
    throw new TypeError("Invalid input, address can't be parsed")
  }
}
Example #9
Source File: linkLibraries.ts    From hardhat-v3-deploy with MIT License 6 votes vote down vote up
linkLibraries = (
  {
    bytecode,
    linkReferences,
  }: {
    bytecode: string
    linkReferences: {
      [fileName: string]: {
        [contractName: string]: { length: number; start: number }[]
      }
    }
  },
  libraries: { [libraryName: string]: string }
): string => {
  Object.keys(linkReferences).forEach((fileName) => {
    Object.keys(linkReferences[fileName]).forEach((contractName) => {
      if (!libraries.hasOwnProperty(contractName)) {
        throw new Error(`Missing link library name ${contractName}`)
      }
      const address = utils
        .getAddress(libraries[contractName])
        .toLowerCase()
        .slice(2)
      linkReferences[fileName][contractName].forEach(
        ({ start: byteStart, length: byteLength }) => {
          const start = 2 + byteStart * 2
          const length = byteLength * 2
          bytecode = bytecode
            .slice(0, start)
            .concat(address)
            .concat(bytecode.slice(start + length, bytecode.length))
        }
      )
    })
  })
  return bytecode
}
Example #10
Source File: utilities.ts    From hypervisor with The Unlicense 6 votes vote down vote up
export function getPositionKey(address: string, lowerTick: number, upperTick: number): string {
    return utils.keccak256(utils.solidityPack(['address', 'int24', 'int24'], [address, lowerTick, upperTick]))
}
Example #11
Source File: eip1271.ts    From walletconnect-v2-monorepo with Apache License 2.0 6 votes vote down vote up
async function isValidSignature(
  address: string,
  sig: string,
  data: string,
  provider: providers.Provider,
  abi = eip1271.spec.abi,
  magicValue = eip1271.spec.magicValue,
): Promise<boolean> {
  let returnValue;
  try {
    returnValue = await new Contract(address, abi, provider).isValidSignature(
      utils.arrayify(data),
      sig,
    );
  } catch (e) {
    return false;
  }
  return returnValue.toLowerCase() === magicValue.toLowerCase();
}
Example #12
Source File: zapin-fetch-data.ts    From wonderland-frontend with MIT License 6 votes vote down vote up
zapinLpData = async (bond: IAllBondData, token: IToken, tokenAmmount: string, network: Networks, slippage: number) => {
    const addresses = getAddresses(network);

    const sellToken = token.isAvax ? ethers.constants.AddressZero : token.address;
    const buyToken = bond.getAddressForReserve(network);

    const url = `https://api.zapper.fi/v1/zap-in/pool/traderjoe/transaction?gasPrice=1000000000000&ownerAddress=${addresses.ZAPIN_ADDRESS}&sellAmount=${tokenAmmount}&sellTokenAddress=${sellToken}&poolAddress=${buyToken}&slippagePercentage=${slippage}&network=avalanche&api_key=96e0cc51-a62e-42ca-acee-910ea7d2a241&skipGasEstimate=true`;

    const { data } = await axios.get(url);

    const zapinInterface = new utils.Interface(TraderZapinContract);

    const { _swapTarget, swapData } = zapinInterface.decodeFunctionData("ZapIn", data.data);

    return [_swapTarget, swapData, data.minTokens];
}
Example #13
Source File: numbers.ts    From connect with GNU Lesser General Public License v3.0 6 votes vote down vote up
formatBn = (
  number: string | BigNumber,
  numberDecimals: string | number,
  formattedDecimals = 2
): string => {
  const formattedNumber = utils.formatUnits(number, numberDecimals)
  const decimalPosition = formattedNumber.indexOf('.')

  if (decimalPosition === -1) {
    return `${formattedNumber}.${'0'.repeat(formattedDecimals)}`
  }

  const decimals = formattedNumber.substring(decimalPosition + 1)
  const decimalsLength = decimals.length

  if (decimalsLength <= formattedDecimals) {
    return `${formattedNumber}${'0'.repeat(formattedDecimals - decimalsLength)}`
  }

  const integer = formattedNumber.substring(0, decimalPosition)
  const roundedDecimals = Math.round(
    parseInt(decimals) / 10 ** (decimalsLength - formattedDecimals)
  )

  const parsedRoundedDecimals = (roundedDecimals === 0)
    ? '0'.repeat(formattedDecimals)
    : roundedDecimals.toString()

  return `${integer}.${parsedRoundedDecimals}`
}
Example #14
Source File: contracts.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
export async function deploy(
  artifact: Artifact,
  args: Array<Param> = [],
  from?: SignerWithAddress,
  libs?: Libraries
): Promise<Contract> {
  if (!args) args = [];
  if (!from) from = await getSigner();
  if (libs) artifact = linkBytecode(artifact, libs);

  const { ethers } = await import('hardhat');
  const factory = await ethers.getContractFactory(artifact.abi, artifact.evm.bytecode.object as utils.BytesLike);
  const deployment = await factory.connect(from).deploy(...args);
  return deployment.deployed();
}
Example #15
Source File: submitting.ts    From safe-tasks with GNU Lesser General Public License v3.0 5 votes vote down vote up
parseTypeDataConfirmation = (safeTxHash: string, data: string): SafeSignature => {
    const signer = utils.recoverAddress(safeTxHash, data)
    return {
        signer, data
    }
}
Example #16
Source File: CrossAnchorBridgeV2__factory.ts    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
static createInterface(): CrossAnchorBridgeV2Interface {
    return new utils.Interface(_abi) as CrossAnchorBridgeV2Interface;
  }
Example #17
Source File: ApeERC20.spec.ts    From apeswap-swap-core with GNU General Public License v3.0 5 votes vote down vote up
{ hexlify, keccak256, defaultAbiCoder, toUtf8Bytes,  } = utils
Example #18
Source File: index.tsx    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
ERC20Contract = new utils.Interface(ERC20ABI)
Example #19
Source File: index.ts    From defillama-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
// SMALL INCOMPATIBILITY: On the old API we don't return ids but we should
export async function getLogs(params: {
  target: Address;
  topic: string;
  keys: string[]; // This is just used to select only part of the logs
  fromBlock: number;
  toBlock: number; // DefiPulse's implementation is buggy and doesn't take this into account
  topics?: string[]; // This is an outdated part of DefiPulse's API which is still used in some old adapters
  chain?: Chain;
}) {
  if(params.toBlock === undefined || params.fromBlock === undefined){
    throw new Error("toBlock and fromBlock need to be defined in all calls to getLogs")
  }
  const filter = {
    address: params.target,
    topics: params.topics ?? [utils.id(params.topic)],
    fromBlock: params.fromBlock,
    toBlock: params.toBlock, // We don't replicate Defipulse's bug because the results end up being the same anyway and hopefully they'll eventually fix it
  };
  let logs: Log[] = [];
  let blockSpread = params.toBlock - params.fromBlock;
  let currentBlock = params.fromBlock;
  while (currentBlock < params.toBlock) {
    const nextBlock = Math.min(params.toBlock, currentBlock + blockSpread);
    try {
      const partLogs = await getProvider(params.chain).getLogs({
        ...filter,
        fromBlock: currentBlock,
        toBlock: nextBlock,
      });
      logs = logs.concat(partLogs);
      currentBlock = nextBlock;
    } catch (e) {
      if (blockSpread >= 2e3) {
        // We got too many results
        // We could chop it up into 2K block spreads as that is guaranteed to always return but then we'll have to make a lot of queries (easily >1000), so instead we'll keep dividing the block spread by two until we make it
        blockSpread = Math.floor(blockSpread / 2);
      } else {
        throw e;
      }
    }
  }
  if (params.keys.length > 0) {
    if (params.keys[0] !== "topics") {
      throw new Error("Unsupported");
    }
    return {
      output: logs.map((log) => log.topics),
    };
  }
  return {
    output: logs,
  };
}
Example #20
Source File: ethersBigNumber.ts    From index-ui with MIT License 5 votes vote down vote up
export function convertToPercentage(bigNumber: BigNumber): string {
  const result = utils.formatUnits(bigNumber, 16)
  return result + '%'
}
Example #21
Source File: index.ts    From eip-712 with MIT License 5 votes vote down vote up
signingKey = new utils.SigningKey(privateKey)
Example #22
Source File: ballot.ts    From panvala with Apache License 2.0 5 votes vote down vote up
/**
 * Transform into the right format to be saved
 */
export async function transform(req, res, next) {
  // Validate input
  const valid = validateBallot(req.body);
  if (!valid) {
    const msg = 'Invalid ballot request data';
    const errors = validateBallot.errors;

    // console.error(errors);
    return res.status(400).json({
      msg,
      errors,
    });
  }

  // Transform into the structure to be inserted into the database
  const { ballot, signature, commitHash } = req.body;
  console.log('ballot:', ballot);
  // TODO: send over the data in a smaller format (JSON.stringify)

  const { epochNumber, salt, voterAddress, choices, delegate } = ballot;

  let voterDelegate;
  if (process.env.NODE_ENV !== 'test') {
    const { gatekeeper } = await getContracts();
    voterDelegate = await gatekeeper.functions.delegate(voterAddress);
  }

  // Regenerate commit message
  const message = voting.generateCommitMessage(commitHash, choices, salt);
  // Recover address from signed message
  const recoveredAddress = utils.verifyMessage(message, signature);
  console.log('recovered:', recoveredAddress);

  // Validate the signature
  if (
    recoveredAddress !== voterAddress &&
    recoveredAddress !== delegate &&
    recoveredAddress !== voterDelegate
  ) {
    return res.status(400).json({
      msg: 'Invalid signature. Recovered signature did not match signer of the commit message.',
      errors: [
        new Error(
          'Invalid signature. Recovered signature did not match signer of the commit message.'
        ),
      ],
    });
  }

  // Need to use capital `VoteChoices` for creation
  // Add the appropriate resource as a field to the choice
  const VoteChoices = Object.keys(choices).map(resource => {
    const choice = { resource, ...choices[resource] };
    return choice;
  });

  // Pass along the transformed data
  req.body = {
    epochNumber,
    voterAddress,
    salt,
    signature,
    VoteChoices,
  };
  // console.log('Processed', req.body);

  next();
}
Example #23
Source File: hooks.ts    From interface-v2 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Need proposal events to get description data emitted from
 * new proposal event.
 */
export function useDataFromEventLogs() {
  const { library } = useActiveWeb3React();
  const [formattedEvents, setFormattedEvents] = useState<any>();
  const govContract = useGovernanceContract();

  useEffect(() => {
    async function fetchData() {
      // create filter for these specific events
      const filter = {
        ...govContract?.filters?.['ProposalCreated'](),
        fromBlock: 0,
        toBlock: 'latest',
      };
      const eventParser = new ethers.utils.Interface(GOV_ABI);

      const pastEvents = await library?.getLogs(filter);
      // reverse events to get them from newest to odlest
      const formattedEventData = pastEvents
        ?.map((event) => {
          const eventParsed = eventParser.parseLog(event).args;
          return {
            description: eventParsed.description,
            details: eventParsed.targets.map((target: string, i: number) => {
              const signature = eventParsed.signatures[i];
              const [name, types] = signature
                .substr(0, signature.length - 1)
                .split('(');

              const calldata = eventParsed.calldatas[i];
              const decoded = utils.defaultAbiCoder.decode(
                types.split(','),
                calldata,
              );

              return {
                target,
                functionSig: name,
                callData: decoded.join(', '),
              };
            }),
          };
        })
        .reverse();
      setFormattedEvents(formattedEventData);
    }
    if (!formattedEvents) {
      fetchData();
    }
  }, [library, formattedEvents, govContract]);

  return formattedEvents;
}
Example #24
Source File: Auth__factory.ts    From nova with GNU Affero General Public License v3.0 5 votes vote down vote up
static createInterface(): AuthInterface {
    return new utils.Interface(_abi) as AuthInterface;
  }