web3-eth-contract#ContractSendMethod TypeScript Examples

The following examples show how to use web3-eth-contract#ContractSendMethod. 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: contractTypes.ts    From webapp with MIT License 6 votes vote down vote up
buildConverterContract = (
  contractAddress?: string,
  web3?: Web3
): ContractMethods<{
  acceptTokenOwnership: () => ContractSendMethod;
  reserves: (reserveAddress: string) => CallReturn<any[]>;
  reserveBalance: (reserveAddress: string) => CallReturn<string>;
  getConnectorBalance: (reserveAddress: string) => CallReturn<string>;
  getReserveBalance: (reserveAdress: string) => CallReturn<string>;
  acceptOwnership: () => ContractSendMethod;
  fund: (fundAmount: string) => ContractSendMethod;
  liquidate: (fundAmount: string) => ContractSendMethod;
  setConversionFee: (ppm: string) => ContractSendMethod;
  addReserve: (
    reserveAddress: string,
    connectorWeight: number
  ) => ContractSendMethod;
  getSaleReturn: (
    toAddress: string,
    wei: string
  ) => CallReturn<{ "0": string; "1": string }>;
  getReturn: (
    fromTokenAddress: string,
    toTokenAddress: string,
    wei: string
  ) => CallReturn<{ "0": string; "1": string }>;
  owner: () => CallReturn<string>;
  version: () => CallReturn<string>;
  connectorTokenCount: () => CallReturn<string>;
  connectorTokens: (index: number) => CallReturn<string>;
  conversionFee: () => CallReturn<string>;
  geometricMean: (weis: string[]) => CallReturn<string>;
}> => buildContract(ABIConverter, contractAddress, web3)
Example #2
Source File: index.ts    From multisig-react with MIT License 6 votes vote down vote up
createTxObject = (
  method: AbiItemExtended,
  contractAddress: string,
  values: Record<string, string>,
): ContractSendMethod => {
  const web3 = getWeb3()
  const contract: any = new web3.eth.Contract([method], contractAddress)
  const { inputs, name = '', signatureHash } = method
  const args = inputs?.map(extractMethodArgs(signatureHash, values)) || []

  return contract.methods[name](...args)
}
Example #3
Source File: index.ts    From multisig-react with MIT License 6 votes vote down vote up
createTxObject = (
  method: AbiItemExtended,
  contractAddress: string,
  values: Record<string, string>,
): ContractSendMethod => {
  const web3 = getWeb3()
  const contract: any = new web3.eth.Contract([method], contractAddress)
  const { inputs, name = '', signatureHash } = method
  const args = inputs?.map(extractMethodArgs(signatureHash, values)) || []

  return contract.methods[name](...args)
}
Example #4
Source File: Contracts.ts    From perpetual with Apache License 2.0 6 votes vote down vote up
private async estimateGas(
    method: ContractSendMethod,
    txOptions: SendOptions,
  ) {
    const estimateOptions: TxOptions = this.toEstimateOptions(txOptions);
    try {
      const gasEstimate = await method.estimateGas(estimateOptions);
      return gasEstimate;
    } catch (error) {
      error.transactionData = {
        ...estimateOptions,
        data: method.encodeABI(),
        to: (method as any)._parent._address,
      };
      throw error;
    }
  }
Example #5
Source File: Contracts.ts    From perpetual with Apache License 2.0 6 votes vote down vote up
public async send(
    method: ContractSendMethod,
    specificOptions: SendOptions = {},
  ): Promise<TxResult> {
    const sendOptions: SendOptions = {
      ...this.defaultOptions,
      ...specificOptions,
    };

    const result = await this._send(method, sendOptions);

    if (
      this._countGasUsage
      && [
        ConfirmationType.Both,
        ConfirmationType.Confirmed,
      ].includes(sendOptions.confirmationType)
    ) {
      // Count gas used.
      const contract: Contract = (method as any)._parent;
      const contractInfo = _.find(this.contractsList, { contract });
      if (contractInfo && !contractInfo.isTest) {
        const gasUsed = (result as TxResult).gasUsed;
        this._cumulativeGasUsed += gasUsed;
        this._gasUsedByFunction.push({ gasUsed, name: (method as any)._method.name });
      }
    }

    return result;
  }
Example #6
Source File: Contracts.ts    From perpetual with Apache License 2.0 6 votes vote down vote up
public async call(
    method: ContractSendMethod,
    specificOptions: CallOptions = {},
  ): Promise<any> {
    const {
      blockNumber,
      ...otherOptions
    } = this.toCallOptions({
      ...this.defaultOptions,
      ...specificOptions,
    });
    return (method as any).call(otherOptions, blockNumber || 'latest');
  }
Example #7
Source File: contractTypes.ts    From webapp with MIT License 6 votes vote down vote up
buildStakingRewardsContract = (
  contractAddress: string,
  web3?: Web3
): ContractMethods<{
  stakeRewards: (maxAmount: string, poolToken: string) => ContractSendMethod;
  claimRewards: () => ContractSendMethod;
  totalClaimedRewards: (provider: string) => CallReturn<string>;
  pendingRewards: (provider: string) => CallReturn<string>;
  store: () => CallReturn<string>;
  pendingReserveRewards: (
    provider: string,
    poolToken: string,
    reserveToken: string
  ) => CallReturn<string>;
  rewardsMultiplier: (
    provider: string,
    poolToken: string,
    reserveToken: string
  ) => CallReturn<string>;
}> => buildContract(ABIStakingRewards, contractAddress, web3)
Example #8
Source File: contractTypes.ts    From webapp with MIT License 6 votes vote down vote up
buildRegistryContract = (
  contractAddress: string,
  web3?: Web3
): ContractMethods<{
  getConvertibleTokens: () => CallReturn<string[]>;
  getConvertibleTokenAnchors: (
    convertibleToken: string
  ) => CallReturn<string[]>;
  getConvertersByAnchors: (anchors: string[]) => CallReturn<string[]>;
  getAnchors: () => CallReturn<string[]>;
  newConverter: (
    type: number,
    smartTokenName: string,
    smartTokenSymbol: string,
    smartTokenDecimals: number,
    maxConversionFee: number,
    reserveTokens: string[],
    reserveWeights: string[]
  ) => ContractSendMethod;
  getLiquidityPoolByConfig: (
    type: number,
    reserveTokens: string[],
    reserveWeight: string[]
  ) => CallReturn<string>;
}> => buildContract(ABIConverterRegistry, contractAddress, web3)
Example #9
Source File: contractTypes.ts    From webapp with MIT License 6 votes vote down vote up
buildNetworkContract = (
  contractAddress: string,
  web3?: Web3
): ContractMethods<{
  rateByPath: (path: string[], amount: string) => CallReturn<string>;
  convertByPath: (
    path: string[],
    amount: string,
    minReturn: string,
    beneficiary: string,
    affiliateAccount: string,
    affiliateFee: number
  ) => ContractSendMethod;
  conversionPath: (
    sourceToken: string,
    destinationToken: string
  ) => CallReturn<string[]>;
}> => buildContract(ABINetworkContract, contractAddress, web3)
Example #10
Source File: contractTypes.ts    From webapp with MIT License 6 votes vote down vote up
buildV2Converter = (
  contractAddress?: string,
  web3?: Web3
): ContractMethods<{
  activate: (
    primaryReserveToken: string,
    primaryReserveOracle: string,
    secondaryReserveOracle: string
  ) => ContractSendMethod;
  reserveStakedBalance: (reserveToken: string) => CallReturn<string>;
  primaryReserveToken: () => CallReturn<string>;
  secondaryReserveToken: () => CallReturn<string>;
  maxStakedBalances: (address: string) => CallReturn<string>;
  maxStakedBalanceEnabled: () => CallReturn<boolean>;
  poolToken: (reserveToken: string) => CallReturn<string>;
  liquidationLimit: (poolToken: string) => CallReturn<string>;
  effectiveReserveWeights: () => CallReturn<{ "0": string; "1": string }>;
  removeLiquidityReturnAndFee: (
    poolToken: string,
    amount: string
  ) => CallReturn<{ "0": string; "1": string }>;
  addLiquidity: (
    reserveTokenAddress: string,
    amount: string,
    minReturn: string
  ) => ContractSendMethod;
  removeLiquidity: (
    poolTokenAddress: string,
    amount: string,
    minReturn: string
  ) => ContractSendMethod;
}> => buildContract(ABIV2Converter, contractAddress, web3)
Example #11
Source File: contractTypes.ts    From webapp with MIT License 6 votes vote down vote up
buildGovernanceContract = (
  contractAddress?: string,
  web3?: Web3
): ContractMethods<{
  voteDuration: () => CallReturn<string>;
  voteLockDuration: () => CallReturn<string>;
  voteLockFraction: () => CallReturn<string>;
  newProposalMinimum: () => CallReturn<string>;
  propose: (executor: string, hash: string) => ContractSendMethod;
  voteFor: (proposalId: string) => ContractSendMethod;
  voteAgainst: (proposalId: string) => ContractSendMethod;
  stake: (amount: string) => ContractSendMethod;
  unstake: (amount: string) => ContractSendMethod;
  decimals: () => CallReturn<string>;
  proposalCount: () => CallReturn<number>;
  proposals: (proposalI: number) => CallReturn<Proposal>;
  votesOf: (voter: string) => CallReturn<string>;
  votesForOf: (voter: string, proposalId: number) => CallReturn<string>;
  votesAgainstOf: (voter: string, proposalId: number) => CallReturn<string>;
  voteLocks: (voter: string) => CallReturn<string>;
  govToken: () => CallReturn<string>;
}> => buildContract(ABIBancorGovernance, contractAddress, web3)
Example #12
Source File: contractTypes.ts    From webapp with MIT License 5 votes vote down vote up
buildExchangeProxyContract = (
  contractAddress: string
): ContractMethods<{
  cancelRfqOrder: (order: StringRfq) => ContractSendMethod;
  batchCancelRfqOrders: (orders: StringRfq[]) => ContractSendMethod;
}> => buildContract(ABIExchangeProxy, contractAddress)
Example #13
Source File: contractTypes.ts    From webapp with MIT License 5 votes vote down vote up
buildLiquidityProtectionContract = (
  contractAddress: string,
  web3?: Web3
): ContractMethods<{
  store: () => CallReturn<string>;
  systemStore: () => CallReturn<string>;
  govToken: () => CallReturn<string>;
  isPoolSupported: (anchor: string) => CallReturn<boolean>;
  protectLiquidity: (
    anchor: string,
    poolTokenWei: string
  ) => ContractSendMethod;
  unprotectLiquidity: (dbId1: string, dbId2: string) => ContractSendMethod;
  addLiquidity: (
    anchor: string,
    reserveAddress: string,
    reserveAmountWei: string
  ) => ContractSendMethod;
  removeLiquidity: (dbId: string, ppmPercent: string) => ContractSendMethod;
  claimBalance: (startIndex: string, endIndex: string) => ContractSendMethod;
  transferLiquidity: (id: string, newProvider: string) => ContractSendMethod;
  removeLiquidityReturn: (
    id: string,
    portion: string,
    removeTimeStamp: string
  ) => CallReturn<{ "0": string; "1": string; "2": string }>;
  poolROI: (
    poolToken: string,
    reserveToken: string,
    reserveAmount: string,
    poolRateN: string,
    poolRateD: string,
    reserveRateN: string,
    reserveRateD: string
  ) => CallReturn<string>;
  settings: () => CallReturn<string>;
  poolAvailableSpace: (
    poolAnchor: string
  ) => CallReturn<{ "0": string; "1": string }>;
}> => buildContract(ABILiquidityProtection, contractAddress, web3)
Example #14
Source File: contractTypes.ts    From webapp with MIT License 5 votes vote down vote up
buildV28ConverterContract = (
  contractAddress?: string,
  web3?: Web3
): ContractMethods<{
  acceptTokenOwnership: () => ContractSendMethod;
  acceptOwnership: () => ContractSendMethod;
  setConversionFee: (ppm: number) => ContractSendMethod;
  addLiquidity: (
    reserveTokens: string[],
    reserveAmounts: string[],
    minReturn: string
  ) => ContractSendMethod;
  removeLiquidity: (
    amount: string,
    reserveTokens: string[],
    reserveMinReturnAmounts: string[]
  ) => ContractSendMethod;
  addReserve: (
    reserveAddress: string,
    connectorWeight: number
  ) => ContractSendMethod;
  getReturn: (
    fromTokenAddress: string,
    toTokenAddress: string,
    wei: string
  ) => CallReturn<{ "0": string; "1": string }>;
  rateAndFee: (
    fromTokenAddress: string,
    toTokenAddress: string,
    wei: string
  ) => CallReturn<{ "0": string; "1": string }>;
  recentAverageRate: (
    tokenAddress: string
  ) => CallReturn<{ "0": string; "1": string }>;
  owner: () => CallReturn<string>;
  version: () => CallReturn<string>;
  converterType: () => CallReturn<string>;
  connectorTokenCount: () => CallReturn<string>;
  connectorTokens: (index: number) => CallReturn<string>;
  conversionFee: () => CallReturn<string>;
  reserveBalance: (reserveToken: string) => CallReturn<string>;
}> => buildContract(ABIConverterV28, contractAddress, web3)
Example #15
Source File: safeHelper.ts    From multisig-react with MIT License 5 votes vote down vote up
getMockedSafeInstance = (safeProps: SafeMethodsProps): GnosisSafe => {
  const { threshold = '1', nonce = '0', isOwnerUserAddress, name = 'safeName', version = '1.0.0' } = safeProps
  return {
    defaultAccount: undefined,
    defaultBlock: undefined,
    defaultChain: undefined,
    defaultCommon: undefined,
    defaultHardfork: undefined,
    handleRevert: false,
    options: undefined,
    transactionBlockTimeout: 0,
    transactionConfirmationBlocks: 0,
    transactionPollingTimeout: 0,
    clone(): GnosisSafe {
      return undefined;
    },
    constructor(jsonInterface: any[], address?: string, options?: ContractOptions): GnosisSafe {
      return undefined;
    },
    deploy(options: DeployOptions): ContractSendMethod {
      return undefined;
    },
    getPastEvents(event: string, options?: PastEventOptions | ((error: Error, event: EventData) => void), callback?: (error: Error, event: EventData) => void): Promise<EventData[]> {
      return undefined;
    },
    once(event: "AddedOwner" | "ExecutionFromModuleSuccess" | "EnabledModule" | "ChangedMasterCopy" | "ExecutionFromModuleFailure" | "RemovedOwner" | "ApproveHash" | "DisabledModule" | "SignMsg" | "ExecutionSuccess" | "ChangedThreshold" | "ExecutionFailure", cb: any): void {
    },
    events: { } as any,
    methods: {
      NAME: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject(name) as NonPayableTransactionObject<string>,
      VERSION: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject(version) as NonPayableTransactionObject<string>,
      addOwnerWithThreshold: (): NonPayableTransactionObject<void> => mockNonPayableTransactionObject() as NonPayableTransactionObject<void>,
      approvedHashes: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject() as NonPayableTransactionObject<string>,
      changeMasterCopy: (): NonPayableTransactionObject<void> => mockNonPayableTransactionObject() as NonPayableTransactionObject<void>,
      changeThreshold: (): NonPayableTransactionObject<void> => mockNonPayableTransactionObject() as NonPayableTransactionObject<void>,
      disableModule: (): NonPayableTransactionObject<void> => mockNonPayableTransactionObject() as NonPayableTransactionObject<void>,
      domainSeparator: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject() as NonPayableTransactionObject<string>,
      enableModule: (): NonPayableTransactionObject<void> => mockNonPayableTransactionObject() as NonPayableTransactionObject<void>,
      execTransactionFromModule: (): NonPayableTransactionObject<boolean> => mockNonPayableTransactionObject() as NonPayableTransactionObject<boolean>,
      execTransactionFromModuleReturnData: (): NonPayableTransactionObject<any> => mockNonPayableTransactionObject() as NonPayableTransactionObject<any>,
      getModules: (): NonPayableTransactionObject<string[]> => mockNonPayableTransactionObject() as NonPayableTransactionObject<string[]>,
      getThreshold: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject(threshold) as NonPayableTransactionObject<string>,
      isOwner: (): NonPayableTransactionObject<boolean> => mockNonPayableTransactionObject(isOwnerUserAddress) as NonPayableTransactionObject<boolean>,
      nonce: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject(nonce) as NonPayableTransactionObject<string>,
      removeOwner: (): NonPayableTransactionObject<void> => mockNonPayableTransactionObject() as NonPayableTransactionObject<void>,
      setFallbackHandler: (): NonPayableTransactionObject<void> => mockNonPayableTransactionObject() as NonPayableTransactionObject<void>,
      signedMessages: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject() as NonPayableTransactionObject<string>,
      swapOwner: (): NonPayableTransactionObject<void> => mockNonPayableTransactionObject() as NonPayableTransactionObject<void>,
      setup: (): NonPayableTransactionObject<void> => mockNonPayableTransactionObject() as NonPayableTransactionObject<void>,
      execTransaction: (): NonPayableTransactionObject<boolean> => mockNonPayableTransactionObject() as NonPayableTransactionObject<boolean>,
      requiredTxGas: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject() as NonPayableTransactionObject<string>,
      approveHash: (): NonPayableTransactionObject<void> => mockNonPayableTransactionObject() as NonPayableTransactionObject<void>,
      signMessage: (): NonPayableTransactionObject<void> => mockNonPayableTransactionObject() as NonPayableTransactionObject<void>,
      isValidSignature: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject() as NonPayableTransactionObject<string>,
      getMessageHash: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject() as NonPayableTransactionObject<string>,
      encodeTransactionData: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject() as NonPayableTransactionObject<string>,
      getTransactionHash: (): NonPayableTransactionObject<string> => mockNonPayableTransactionObject() as NonPayableTransactionObject<string>,
    } as any
  }
}
Example #16
Source File: send-transaction.ts    From ethereum-sdk with MIT License 5 votes vote down vote up
export async function sentTx(source: ContractSendMethod, options: SendOptions): Promise<string> {
	const event = source.send({ ...options, gas: 3000000 })
	return waitForHash(event)
}
Example #17
Source File: index.ts    From ethereum-sdk with MIT License 5 votes vote down vote up
private readonly sendMethod: ContractSendMethod
Example #18
Source File: Contracts.ts    From perpetual with Apache License 2.0 4 votes vote down vote up
private async _send( // tslint:disable-line:function-name
    method: ContractSendMethod,
    sendOptions: SendOptions = {},
  ): Promise<TxResult> {
    const {
      confirmations,
      confirmationType,
      gasMultiplier,
      ...txOptions
    } = sendOptions;

    if (!Object.values(ConfirmationType).includes(confirmationType)) {
      throw new Error(`Invalid confirmation type: ${confirmationType}`);
    }

    if (confirmationType === ConfirmationType.Simulate || !txOptions.gas) {
      const gasEstimate = await this.estimateGas(method, txOptions);
      txOptions.gas = Math.floor(gasEstimate * gasMultiplier);

      if (confirmationType === ConfirmationType.Simulate) {
        return {
          gasEstimate,
          gas: txOptions.gas,
        };
      }
    }

    const promi: PromiEvent<Contract> = method.send(this.toNativeSendOptions(txOptions) as any);

    let hashOutcome = OUTCOMES.INITIAL;
    let confirmationOutcome = OUTCOMES.INITIAL;

    let transactionHash: string;
    let hashPromise: Promise<string>;
    let confirmationPromise: Promise<TransactionReceipt>;

    if ([
      ConfirmationType.Hash,
      ConfirmationType.Both,
    ].includes(confirmationType)) {
      hashPromise = new Promise(
        (resolve, reject) => {
          promi.on('error', (error: Error) => {
            if (hashOutcome === OUTCOMES.INITIAL) {
              hashOutcome = OUTCOMES.REJECTED;
              reject(error);
              (promi as any).off();
            }
          });

          promi.on('transactionHash', (txHash: string) => {
            if (hashOutcome === OUTCOMES.INITIAL) {
              hashOutcome = OUTCOMES.RESOLVED;
              resolve(txHash);
              if (confirmationType !== ConfirmationType.Both) {
                (promi as any).off();
              }
            }
          });
        },
      );
      transactionHash = await hashPromise;
    }

    if ([
      ConfirmationType.Confirmed,
      ConfirmationType.Both,
    ].includes(confirmationType)) {
      confirmationPromise = new Promise(
        (resolve, reject) => {
          promi.on('error', (error: Error) => {
            if (
              confirmationOutcome === OUTCOMES.INITIAL
              && (
                confirmationType === ConfirmationType.Confirmed
                || hashOutcome === OUTCOMES.RESOLVED
              )
            ) {
              confirmationOutcome = OUTCOMES.REJECTED;
              reject(error);
              (promi as any).off();
            }
          });

          if (confirmations) {
            promi.on('confirmation', (confNumber: number, receipt: TransactionReceipt) => {
              if (confNumber >= confirmations) {
                if (confirmationOutcome === OUTCOMES.INITIAL) {
                  confirmationOutcome = OUTCOMES.RESOLVED;
                  resolve(receipt);
                  (promi as any).off();
                }
              }
            });
          } else {
            promi.on('receipt', (receipt: TransactionReceipt) => {
              confirmationOutcome = OUTCOMES.RESOLVED;
              resolve(receipt);
              (promi as any).off();
            });
          }
        },
      );
    }

    if (confirmationType === ConfirmationType.Hash) {
      return this.normalizeResponse({ transactionHash });
    }

    if (confirmationType === ConfirmationType.Confirmed) {
      return confirmationPromise;
    }

    return this.normalizeResponse({
      transactionHash,
      confirmation: confirmationPromise,
    });
  }