web3-utils#AbiItem TypeScript Examples

The following examples show how to use web3-utils#AbiItem. 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: eth-like-web3-private.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * executes method of smart-contract and resolve the promise without waiting for the transaction to be included in the block
   * @param contractAddress address of smart-contract which method is to be executed
   * @param contractAbi abi of smart-contract which method is to be executed
   * @param methodName executing method name
   * @param methodArguments executing method arguments
   * @return smart-contract method returned value
   */
  public executeContractMethodWithOnHashResolve(
    contractAddress: string,
    contractAbi: AbiItem[],
    methodName: string,
    methodArguments: unknown[]
  ): Promise<unknown> {
    const contract = new this.web3.eth.Contract(contractAbi, contractAddress);

    return new Promise((resolve, reject) => {
      this.emitTransaction();
      contract.methods[methodName](...methodArguments)
        .send({
          from: this.address,
          ...(this.defaultMockGas && { gas: this.defaultMockGas })
        })
        .on('transactionHash', resolve)
        .on('error', (err: Web3Error) => {
          console.error(`Tokens approve error. ${err}`);
          reject(EthLikeWeb3PrivateService.parseError(err));
        });
    });
  }
Example #2
Source File: web3-private.ts    From rubic-sdk with GNU General Public License v3.0 6 votes vote down vote up
/**
     * @description sends ERC-20 tokens and resolve the promise when the transaction is included in the block
     * @param contractAddress address of the smart-contract corresponding to the token
     * @param toAddress token receiver address
     * @param amount integer tokens amount to send (pre-multiplied by 10 ** decimals)
     * @param [options] additional options
     * @param [options.onTransactionHash] callback to execute when transaction enters the mempool
     * @return transaction receipt
     */
    public async transferTokens(
        contractAddress: string,
        toAddress: string,
        amount: string | BigNumber,
        options: TransactionOptions = {}
    ): Promise<TransactionReceipt> {
        const contract = new this.web3.eth.Contract(ERC20_TOKEN_ABI as AbiItem[], contractAddress);

        return new Promise((resolve, reject) => {
            contract.methods
                .transfer(toAddress, Web3Private.stringifyAmount(amount))
                .send({
                    from: this.address,
                    ...(options.gas && { gas: Web3Private.stringifyAmount(options.gas) }),
                    ...(options.gasPrice && {
                        gasPrice: Web3Private.stringifyAmount(options.gasPrice)
                    })
                })
                .on('transactionHash', options.onTransactionHash || (() => {}))
                .on('receipt', resolve)
                .on('error', (err: Web3Error) => {
                    console.error(`Tokens transfer error. ${err}`);
                    reject(Web3Private.parseError(err));
                });
        });
    }
Example #3
Source File: Networks.ts    From compound-protocol with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export async function loadContractData(
  world: World,
  networks: Networks,
  networksABI: Networks
): Promise<[World, string[]]> {
  // Pull off contracts value and the rest is "extra"
  let contractInfo: string[] = [];
  let contracts = networks.get('Contracts') || Map({});

  world = contracts.reduce((world: World, address: string, name: string) => {
    let abi: AbiItem[] = networksABI.has(name) ? networksABI.get(name).toJS() : [];
    let contract = new world.web3.eth.Contract(abi, address, {});

    world = updateEventDecoder(world, contract);

    contractInfo.push(`${name}: ${address}`);

    // Store the contract
    // XXXS
    return world.setIn(['contractIndex', (<any>contract)._address.toLowerCase()], setContractName(name, <Contract><unknown>contract));
  }, world);

  world = world.update('contractData', contractData => contractData.mergeDeep(networks));

  return [world, contractInfo];
}
Example #4
Source File: gmiStaking.ts    From index-ui with MIT License 6 votes vote down vote up
getAmountOfStakedTokens = async (
  provider: provider,
  contractAddress: string
) => {
  const web3 = new Web3(provider)
  const contract = new web3.eth.Contract(
    StakeABI as unknown as AbiItem,
    contractAddress
  )
  return await contract.methods.totalSupply().call()
}
Example #5
Source File: chi.ts    From dsa-connect with MIT License 6 votes vote down vote up
chi: AbiItem[] = [
  {
    inputs: [{ internalType: 'uint256', name: 'amt', type: 'uint256' }],
    name: 'burn',
    outputs: [],
    stateMutability: 'payable',
    type: 'function',
  },
  {
    inputs: [],
    name: 'connectorID',
    outputs: [
      { internalType: 'uint256', name: 'model', type: 'uint256' },
      { internalType: 'uint256', name: 'id', type: 'uint256' },
    ],
    stateMutability: 'view',
    type: 'function',
  },
  {
    inputs: [{ internalType: 'uint256', name: 'amt', type: 'uint256' }],
    name: 'mint',
    outputs: [],
    stateMutability: 'payable',
    type: 'function',
  },
  {
    inputs: [],
    name: 'name',
    outputs: [{ internalType: 'string', name: '', type: 'string' }],
    stateMutability: 'view',
    type: 'function',
  },
]
Example #6
Source File: eth-like-web3-private.service.ts    From rubic-app with GNU General Public License v3.0 5 votes vote down vote up
/**
   * tries to execute method of smart-contract and resolve the promise when the transaction is included in the block or rejects the error
   * @param contractAddress address of smart-contract which method is to be executed
   * @param contractAbi abi of smart-contract which method is to be executed
   * @param methodName executing method name
   * @param methodArguments executing method arguments
   * @param [options] additional options
   * @param [options.value] amount in Wei amount to be attached to the transaction
   * @param [options.gas] gas limit to be attached to the transaction
   * @param allowError Check error and decides to execute contact if it needed.
   * @param skipChecks Flag to skip call method before execute.
   */
  public async tryExecuteContractMethod(
    contractAddress: string,
    contractAbi: AbiItem[],
    methodName: string,
    methodArguments: unknown[],
    options: TransactionOptions = {},
    allowError?: (err: Web3Error) => boolean,
    skipChecks?: boolean
  ): Promise<TransactionReceipt> {
    const contract = new this.web3.eth.Contract(contractAbi, contractAddress);

    try {
      if (!skipChecks) {
        await contract.methods[methodName](...methodArguments).call({
          from: this.address,
          ...(options.value && { value: options.value }),
          ...((options.gas || this.defaultMockGas) && {
            gas: options.gas || this.defaultMockGas
          })
          // ...(options.gasPrice && { gasPrice: options.gasPrice }) doesn't work on mobile
        });
      }
      return this.executeContractMethod(
        contractAddress,
        contractAbi,
        methodName,
        methodArguments,
        options
      );
    } catch (err) {
      if (allowError?.(err)) {
        return this.executeContractMethod(
          contractAddress,
          contractAbi,
          methodName,
          methodArguments,
          options
        );
      }
      console.error('Method execution error:', err);
      throw EthLikeWeb3PrivateService.parseError(err);
    }
  }
Example #7
Source File: web3-private.ts    From rubic-sdk with GNU General Public License v3.0 5 votes vote down vote up
/**
     * @description tries to execute method of smart-contract and resolve the promise when the transaction is included in the block or rejects the error
     * @param contractAddress address of smart-contract which method is to be executed
     * @param contractAbi abi of smart-contract which method is to be executed
     * @param methodName executing method name
     * @param methodArguments executing method arguments
     * @param [options] additional options
     * @param [options.value] amount in Wei amount to be attached to the transaction
     * @param [options.gas] gas limit to be attached to the transaction
     * @param allowError Check error and decides to execute contact if it needed.
     */
    public async tryExecuteContractMethod(
        contractAddress: string,
        contractAbi: AbiItem[],
        methodName: string,
        methodArguments: unknown[],
        options: TransactionOptions = {},
        allowError?: (err: Web3Error) => boolean
    ): Promise<TransactionReceipt> {
        const contract = new this.web3.eth.Contract(contractAbi, contractAddress);

        try {
            const gas = await contract.methods[methodName](...methodArguments).estimateGas({
                from: this.address,
                ...(options.value && { value: Web3Private.stringifyAmount(options.value) }),
                ...(options.gas && { gas: Web3Private.stringifyAmount(options.gas) }),
                ...(options.gasPrice && {
                    gasPrice: Web3Private.stringifyAmount(options.gasPrice)
                })
            });
            return await this.executeContractMethod(
                contractAddress,
                contractAbi,
                methodName,
                methodArguments,
                {
                    ...options,
                    gas: options.gas || Web3Pure.calculateGasMargin(gas, 1.15)
                }
            );
        } catch (err: unknown) {
            if (allowError && allowError(err as Web3Error)) {
                return this.executeContractMethod(
                    contractAddress,
                    contractAbi,
                    methodName,
                    methodArguments,
                    options
                );
            }
            console.error('Method execution error: ', err);
            throw Web3Private.parseError(err as Web3Error);
        }
    }
Example #8
Source File: EventBuilder.ts    From compound-protocol with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
export async function buildContractFetcher<T extends Contract>(world: World, contractName: string, implicit: boolean) {

  let abis: AbiItem[] = await world.saddle.abi(contractName);

  function fetchers() {
    async function buildOutput(world: World, fn: string, inputs: object, output: AbiItem): Promise<Value> {
      const callable = <Callable<any>>(inputs['contract'].methods[fn](...Object.values(inputs).slice(1)));
      let value = await callable.call();
      let { builder } = typeMappings()[output.type] || {};

      if (!builder) {
        throw new Error(`Unknown ABI Output Type: ${output.type} of \`${fn}\` in ${contractName}`);
      }

      return builder(value);
    }

    return abis.filter(({name}) => !!name).map((abi: any) => {
      let eventName = getEventName(abi.name);
      let inputNames = abi.inputs.map((input) => getEventName(input.name));
      let args = [
        new Arg("contract", getContractObjectFn(contractName, implicit), implicit ? { implicit: true } : {})
      ].concat(abi.inputs.map((input) => buildArg(contractName, abi.name, input)));
      return new Fetcher<object, Value>(`
          #### ${eventName}

          * "${eventName} ${inputNames.join(" ")}" - Returns the result of \`${abi.name}\` function
        `,
        eventName,
        args,
        (world, inputs) => buildOutput(world, abi.name, inputs, abi.outputs[0]),
        { namePos: implicit ? 0 : 1 }
      )
    });
  }

  async function getValue(world: World, event: Event): Promise<Value> {
    return await getFetcherValue<any, any>(contractName, fetchers(), world, event);
  }

  let fetcher = new Fetcher<{ res: Value }, Value>(
    `
      #### ${contractName}

      * "${contractName} ...args" - Returns ${contractName} value
    `,
    contractName,
    [new Arg('res', getValue, { variadic: true })],
    async (world, { res }) => res,
    { subExpressions: fetchers() }
  )

  return fetcher;
}
Example #9
Source File: airdrop.ts    From index-ui with MIT License 5 votes vote down vote up
getAirdropContract = (provider: provider, address: string) => {
  const web3 = new Web3(provider)
  const contract = new web3.eth.Contract(
    AirdropABI as unknown as AbiItem,
    address
  )
  return contract
}
Example #10
Source File: aave_claim.ts    From dsa-connect with MIT License 5 votes vote down vote up
aave_claim: AbiItem[] = [{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address[]","name":"assets","type":"address[]"},{"indexed":false,"internalType":"uint256","name":"amt","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"getId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"setId","type":"uint256"}],"name":"LogClaimed","type":"event"},{"inputs":[{"internalType":"address[]","name":"assets","type":"address[]"},{"internalType":"uint256","name":"amt","type":"uint256"},{"internalType":"uint256","name":"getId","type":"uint256"},{"internalType":"uint256","name":"setId","type":"uint256"}],"name":"claim","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"connectorID","outputs":[{"internalType":"uint256","name":"_type","type":"uint256"},{"internalType":"uint256","name":"_id","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"}]