web3-core#TransactionConfig TypeScript Examples

The following examples show how to use web3-core#TransactionConfig. 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: index.ts    From tatum-js with MIT License 6 votes vote down vote up
updateCashbackForAuthorSignedTransaction = async (
  body: ChainUpdateCashbackErc721,
  web3: EvmBasedWeb3,
  provider?: string,
) => {
  const { fromPrivateKey, cashbackValue, tokenId, fee, contractAddress, nonce, signatureId } = body

  const client = await web3.getClient(provider, fromPrivateKey)

  const contract = new client.eth.Contract(Erc721Token.abi as any, contractAddress)

  const tx: TransactionConfig = {
    from: undefined,
    to: contractAddress.trim(),
    data: contract.methods
      .updateCashbackForAuthor(
        tokenId,
        `0x${new BigNumber(client.utils.toWei(cashbackValue, 'ether')).toString(16)}`,
      )
      .encodeABI(),
    nonce,
  }
  return await evmBasedUtils.prepareSignedTransactionAbstraction(
    client,
    tx,
    web3,
    signatureId,
    fromPrivateKey,
    fee?.gasLimit,
    fee?.gasPrice,
  )
}
Example #2
Source File: transaction.ts    From dsa-connect with MIT License 6 votes vote down vote up
/**
   * Speed up transaction.
   *
   * @param params.transactionHash - Transaction hash.
   * @param params.gasPrice - Transaction hash.
   * @returns Transaction hash.
   */
  speedUp = async (
    dsa: DSA,
    params: { transactionHash: string; gasPrice: NonNullable<TransactionConfig['gasPrice']> }
  ) => {
    if (!params.transactionHash) throw new Error("Parameter 'transactionHash' is not defined.")
    if (!params.gasPrice) throw new Error("Parameter 'gasPrice' is not defined.")

    const userAddress = await this.dsa.internal.getAddress()

    if (!userAddress) throw new Error('User address is not defined.')

    const transaction = await this.dsa.web3.eth.getTransaction(params.transactionHash)

    if (transaction.from.toLowerCase() !== userAddress.toLowerCase()) throw new Error("'from' address doesnt match.")

    const gasPrice = typeof params.gasPrice !== 'number' ? params.gasPrice : params.gasPrice.toFixed(0)

    const transactionConfig: TransactionConfig = {
      from: transaction.from,
      to: transaction.to ?? undefined,
      value: transaction.value,
      data: transaction.input,
      gasPrice: gasPrice,
      gas: transaction.gas,
      nonce: transaction.nonce,
    }

    const transactionHash = await this.send(transactionConfig)

    return transactionHash
  }
Example #3
Source File: limit-order-rfq.helpers.ts    From limit-order-protocol-utils with MIT License 6 votes vote down vote up
/* eslint-enable max-lines-per-function */

/* eslint-disable max-lines-per-function */
export async function cancelOrder(params: CancelingParams): Promise<string> {
    const contractAddress = contractAddresses[params.chainId as ChainId];
    const web3 = new Web3(
        new Web3.providers.HttpProvider(rpcUrls[params.chainId as ChainId])
    );
    const providerConnector = new PrivateKeyProviderConnector(
        params.privateKey,
        web3
    );
    const walletAddress = web3.eth.accounts.privateKeyToAccount(
        params.privateKey
    ).address;

    const limitOrderProtocolFacade = new LimitOrderProtocolFacade(
        contractAddress,
        providerConnector
    );

    const callData = limitOrderProtocolFacade.cancelRFQOrder(params.orderInfo);
    const txConfig: TransactionConfig = {
        to: contractAddress,
        from: walletAddress,
        data: callData,
        value: '0',
        gas: 50_000,
        gasPrice: gweiToWei(params.gasPrice),
        nonce: await web3.eth.getTransactionCount(walletAddress),
    };

    return sendSignedTransaction(web3, txConfig, params.privateKey);
}
Example #4
Source File: web3-pure.ts    From rubic-sdk with GNU General Public License v3.0 6 votes vote down vote up
static encodeMethodCall(
        contractAddress: string,
        contractAbi: AbiItem[],
        method: string,
        parameters: unknown[] = [],
        value?: string,
        options: TransactionGasParams = {}
    ): TransactionConfig {
        const contract = new this.web3Eth.Contract(contractAbi);
        const data = contract.methods[method](...parameters).encodeABI();
        return {
            to: contractAddress,
            data,
            value,
            gas: options.gas,
            gasPrice: options.gasPrice
        };
    }
Example #5
Source File: cast-helpers.ts    From dsa-connect with MIT License 6 votes vote down vote up
/**
   * Returns the estimated gas cost.
   *
   * @param params.from the from address
   * @param params.to the to address
   * @param params.value eth value
   * @param params.spells cast spells
   */
  estimateGas = async (
    params: { spells: Spells } & Pick<TransactionConfig, 'from' | 'to' | 'value'>
  ) => {

    const to = params.to ?? this.dsa.instance.address

    if (to === Addresses.genesis)
      throw new Error(
        `Please configure the DSA instance by calling dsa.setInstance(dsaId). More details: https://docs.instadapp.io/setup`
      )

    const { targets, spells } = this.dsa.internal.encodeSpells(params)
    const args = [targets, spells, this.dsa.origin]
    let from = params.from;
    if (!from) {
      const fromFetch = await this.dsa.internal.getAddress()
      from = fromFetch ? fromFetch : ''
    }

    const value = params.value ?? '0'
    
    const abi = this.dsa.internal.getInterface(Abi.core.versions[this.dsa.instance.version].account, 'cast')
   
    if (!abi) throw new Error('Abi is not defined.')

    const estimatedGas = await this.dsa.internal.estimateGas({ abi, to, from, value, args })
     
    return estimatedGas     
  }
Example #6
Source File: egld.tx.ts    From tatum-js with MIT License 6 votes vote down vote up
prepareTransferEsdtSignedTransaction = async (body: TransferEgld) => {
  const { fromPrivateKey, signatureId, from, to, fee, data } = body

  const sender = from || (await generateAddressFromPrivatekey(fromPrivateKey as string))
  const parsedData = data && JSON.parse(data)
  const preparedData = parsedData
    ? await prepareEsdtTransferData({
        ...(parsedData as EsdtTransfer),
        service: parsedData.service || 'ESDTTransfer',
      })
    : `{ service: ESDTTransfer }`

  const tx: TransactionConfig = {
    from: sender,
    to,
    gasPrice: fee?.gasPrice,
    gas: fee?.gasLimit,
    data: preparedData,
  }

  return await prepareSignedTransactionAbstraction(tx, signatureId, fromPrivateKey)
}
Example #7
Source File: erc20.ts    From dsa-connect with MIT License 6 votes vote down vote up
/**
    * Approve Token Tx Obj
    */
   async approveTxObj(params: Erc20InputParams): Promise<TransactionConfig> {
     if (!params.to) {
       throw new Error("Parameter 'to' is missing")
     }
     if (!params.from) {
       params.from = await this.dsa.internal.getAddress()
     }

     let txObj: TransactionConfig;

     if (["eth", TokenInfo.eth.address].includes(params.token.toLowerCase())) {
       throw new Error("ETH does not require approve.") 
     } else {
       const toAddr: string = params.to
       params.to = this.dsa.internal.filterAddress(params.token)
       const contract = new this.dsa.web3.eth.Contract(Abi.basics.erc20, params.to)
       const data: string = contract.methods
         .approve(toAddr, params.amount)
         .encodeABI()

       txObj = await this.dsa.internal.getTransactionConfig({
        from: params.from,
        to: params.to,
        data: data,
        gas: params.gas,
        gasPrice: params.gasPrice,
        nonce: params.nonce,
        value: 0,
      } as GetTransactionConfigParams)
     }

     return txObj
   }
Example #8
Source File: egld.tx.ts    From tatum-js with MIT License 6 votes vote down vote up
prepareSignedTransaction = async (body: TransferEgld) => {
  const { fromPrivateKey, signatureId, from, to, amount, fee, data } = body

  const tx: TransactionConfig = {
    from: from || 0,
    to: to,
    value: amount,
    gasPrice: fee?.gasPrice,
    gas: fee?.gasLimit,
    data,
  }

  return await prepareSignedTransactionAbstraction(tx, signatureId, fromPrivateKey)
}
Example #9
Source File: erc721.ts    From dsa-connect with MIT License 6 votes vote down vote up
/**
    * Approve Token Tx Obj
    */
   async approveTxObj(params: Erc721InputParams): Promise<TransactionConfig> {
     if (!params.to) {
       throw new Error("Parameter 'to' is missing")
     }
     if (!params.from) {
       params.from = await this.dsa.internal.getAddress()
     }

     let txObj: TransactionConfig;

      const toAddr: string = params.to
      params.to = this.dsa.internal.filterAddress(params.token)
      const contract = new this.dsa.web3.eth.Contract(Abi.basics.erc20, params.to)
      const data: string = contract.methods
        .approve(toAddr, params.tokenId)
        .encodeABI()

      txObj = await this.dsa.internal.getTransactionConfig({
      from: params.from,
      to: params.to,
      data: data,
      gas: params.gas,
      gasPrice: params.gasPrice,
      nonce: params.nonce,
      value: 0,
    } as GetTransactionConfigParams)

    return txObj
   }
Example #10
Source File: limit-order-rfq.utils.test.ts    From limit-order-protocol-utils with MIT License 5 votes vote down vote up
describe.skip('Limit order rfq utils', () => {
    const chainId = 56;
    const privateKey = 'SET YOUR PRIVATE KEY';

    it('Fill RFQ order', async () => {
        const order = createOrder({
            privateKey,
            chainId,
            orderId: 1,
            expiresIn: Math.ceil((Date.now() + 20_000) / 1000),
            makerAssetAddress: '0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3', // DAI
            takerAssetAddress: '0x111111111117dc0aa78b770fa6a738034120c302', // 1inch
            makerAmount: '100000000000000000',
            takerAmount: '23000000000000000',
        });

        const txHash = await fillOrder(
            {
                privateKey,
                chainId,
                gasPrice: 15, // GWEI
                order: JSON.stringify(order),
                makerAmount: order.makingAmount,
                takerAmount: '0',
            },
            order
        );

        expect(txHash).toBe('tx hash');
    });

    it('Fill limit order', async () => {
        const contractAddress = contractAddresses[chainId];
        const web3 = new Web3(rpcUrls[chainId]);
        const providerConnector = new PrivateKeyProviderConnector(
            privateKey,
            web3
        );
        const walletAddress = web3.eth.accounts
            .privateKeyToAccount(privateKey)
            .address.toLowerCase();

        const limitOrderBuilder = new LimitOrderBuilder(
            contractAddress,
            chainId,
            providerConnector
        );

        const limitOrderProtocolFacade = new LimitOrderProtocolFacade(
            contractAddress,
            providerConnector
        );

        const order = limitOrderBuilder.buildLimitOrder({
            makerAddress: walletAddress,
            makerAssetAddress: '0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3', // DAI
            takerAssetAddress: '0x111111111117dc0aa78b770fa6a738034120c302', // 1inch
            makerAmount: '100000000000000000',
            takerAmount: '23000000000000000',
        });

        const typedData = limitOrderBuilder.buildLimitOrderTypedData(order);
        const signature = await limitOrderBuilder.buildOrderSignature(
            walletAddress,
            typedData
        );

        const callData = limitOrderProtocolFacade.fillLimitOrder(
            order,
            signature,
            order.makingAmount,
            '0',
            '100000000000000001'
        );

        const txConfig: TransactionConfig = {
            to: contractAddress,
            from: walletAddress,
            data: callData,
            value: '0',
            gas: 120_000,
            gasPrice: gweiToWei(15),
            nonce: await web3.eth.getTransactionCount(walletAddress),
        };

        const txHash = await sendSignedTransaction(web3, txConfig, privateKey);

        expect(txHash).toBe('tx hash');
    });
});
Example #11
Source File: uniswap-contract-strongly-typed-example.ts    From ethereum-abi-types-generator with MIT License 5 votes vote down vote up
/**
   * Make the trade encoding the data and sending the transaction
   * @param ethAmount The eth amount
   * @param minTokens The min tokens
   */
  public async tradeWithBuildingTransactionConfig(
    ethAmount: BigNumber,
    minTokens: BigNumber
  ): Promise<string> {
    const exchangeAddress = await this.getExchangeAddress(
      AbiExamples.funContractAddress
    );

    const exchangeContract = this.getExchangeContractForTokenByExchangeAddress(
      exchangeAddress
    );

    // you can build the data up like this if you want?
    const data = exchangeContract.methods
      .ethToTokenSwapInput(
        web3.utils.toHex(minTokens as any),
        this.generateTradeDeadlineUnixTime()
      )
      .encodeABI();

    this.logUniswapOutput(`Encoded abi and generated data ${data}`);
    // Uniswap class - Encoded abi and generated data 0xf39b5b9b0000000000000000000000000000000000000000000000000000000000000384000000000000000000000000000000000000000000000000000000005eac075c

    // and build up a `TransactionConfig`
    const transactionConfig: TransactionConfig = {
      from: mockEthereumAddress,
      to: exchangeAddress,
      data,
      value: web3.utils.toWei(ethAmount.toFixed(), 'ether'),
      gas: web3.utils.numberToHex(21912),
    };

    this.logUniswapOutput(
      `Transaction config built up ${JSON.stringify(transactionConfig)}`
    );
    // Uniswap class - Transaction config built up {"from":"0x419D0d8BdD9aF5e606Ae2232ed285Aff190E711b","to":"0x60a87cC7Fca7E53867facB79DA73181B1bB4238B","data":"0xf39b5b9b0000000000000000000000000000000000000000000000000000000000000384000000000000000000000000000000000000000000000000000000005eac075c","value":"10000000000000000"}

    // obviously if your using a wallet provider do your standard
    // web3.eth.sendTransaction :)
    const signedTransaction = await web3.eth.accounts.signTransaction(
      transactionConfig,
      '0x0123456789012345678901234567890123456789012345678901234567890123'
    );

    // and send it through web3...
    // not actually going to send here as we have no private keys
    // but if you were using metamask or other wallet providers it would trigger a signer
    // this is merely an example
    const transactionReceipt = (await web3.eth.sendSignedTransaction(
      signedTransaction.rawTransaction!
    )) as TransactionReceipt;

    this.logUniswapOutput(
      `Transaction sent ${transactionReceipt.transactionHash}`
    );
    // Uniswap class - Transaction sent 0x972c2155137efecb126dc5f4f72fb451753eab8f5fce45aad73e00861ae27fe1

    return transactionReceipt.transactionHash;
  }
Example #12
Source File: evm-based.auction.ts    From tatum-js with MIT License 5 votes vote down vote up
auctionApproveErc20TransferSignedTransaction = async (
  body: ApproveNftTransfer,
  web3: EvmBasedWeb3,
  provider?: string,
) => {
  const client = web3.getClient(provider)
  const amount = new BigNumber(body.amount)
    .multipliedBy(
      new BigNumber(10).pow(
        // TODO any type
        await new client.eth.Contract(Erc20Token.abi as any, body.contractAddress.trim()).methods
          .decimals()
          .call(),
      ),
    )
    .toString(16)
  const params = [body.spender.trim(), `0x${amount}`]
  body.amount = '0'

  const methodName = 'approve'
  const methodAbi = MarketplaceSmartContract.abi.find((a) => a.name === methodName) as AbiItem
  const contract = new client.eth.Contract([methodAbi])
  const tx: TransactionConfig = {
    from: 0,
    to: body.contractAddress.trim(),
    value: amount ? `0x${new BigNumber(toWei(amount, 'ether')).toString(16)}` : undefined,
    data: contract.methods[methodName as string](...params).encodeABI(),
    nonce: body.nonce,
  }

  return evmBasedUtils.prepareSignedTransactionAbstraction(
    client,
    tx,
    web3,
    body.signatureId,
    body.fromPrivateKey,
    body.fee?.gasLimit,
    body.fee?.gasPrice,
  )
}
Example #13
Source File: WEB3_Driver.ts    From core with MIT License 5 votes vote down vote up
buildProposal = async (body: any) => {
    const provider = new Web3.providers.HttpProvider(
      this.getProposalEndpoint()
    );

    const {
      fromPrivateKey,
      to,
      amount,
      currency,
      fee,
      data,
      nonce,
      signatureId,
    } = body;

    const client = new Web3(provider);
    client.eth.accounts.wallet.add(fromPrivateKey);
    client.eth.defaultAccount = client.eth.accounts.wallet[0].address;

    let tx: TransactionConfig;
    if (currency === this.nativeAssetSymbol) {
      tx = {
        from: 0,
        to: to.trim(),
        value: client.utils.toWei(`${amount}`, 'ether'),
        data: data
          ? client.utils.isHex(data)
            ? client.utils.stringToHex(data)
            : client.utils.toHex(data)
          : undefined,
        nonce,
      };
    } else {
      const contract = new client.eth.Contract(
        // @ts-ignore
        [TRANSFER_METHOD_ABI],
        this.assetConfig.contract
      );
      const digits = new BigNumber(10).pow(this.assetConfig.decimals!);
      tx = {
        from: 0,
        to: this.assetConfig.contract!,
        data: contract.methods
          .transfer(
            to.trim(),
            `0x${new BigNumber(amount).multipliedBy(digits).toString(16)}`
          )
          .encodeABI(),
        nonce,
      };
    }

    const gasPrice = client.utils.toWei(fee.gasPrice, 'gwei');
    tx = {
      ...tx,
      gasPrice,
    };

    if (!signatureId) {
      tx.gas = fee?.gasLimit ?? (await client.eth.estimateGas(tx));
    }

    return {
      signatureId: signatureId,
      fromPrivateKey: fromPrivateKey,
      fee: {
        gasLimit: tx.gas,
        gasPrice: fee.gasPrice,
      },
      proposal: signatureId ? JSON.stringify(tx) : tx,
    };
  };
Example #14
Source File: instant-trade.ts    From rubic-sdk with GNU General Public License v3.0 5 votes vote down vote up
public abstract encode(options: EncodeTransactionOptions): Promise<TransactionConfig>;
Example #15
Source File: index.ts    From tatum-js with MIT License 5 votes vote down vote up
sellAsset = async (body: ChainSellAssetOnMarketplace, web3: EvmBasedWeb3, provider?: string) => {
  const client = web3.getClient(provider, body.fromPrivateKey)
  const {
    contractAddress,
    erc20Address,
    nftAddress,
    seller,
    listingId,
    amount,
    tokenId,
    price,
    isErc721,
    signatureId,
    fromPrivateKey,
    nonce,
    fee,
  } = body

  const smartContractMethodName = 'createListing'
  const smartContractParams = [
    listingId,
    isErc721,
    nftAddress.trim(),
    tokenId,
    price,
    seller.trim(),
    amount ?? '0',
    erc20Address ?? '0x0000000000000000000000000000000000000000',
  ]

  // TODO remove any type
  const data = new client.eth.Contract(ListingSmartContract.abi as any).methods[smartContractMethodName](
    ...smartContractParams,
  ).encodeABI()

  if (contractAddress) {
    const tx: TransactionConfig = {
      from: undefined,
      data,
      to: contractAddress.trim(),
      nonce: nonce,
    }

    return evmBasedUtils.prepareSignedTransactionAbstraction(
      client,
      tx,
      web3,
      signatureId,
      fromPrivateKey,
      fee?.gasLimit,
      fee?.gasPrice,
    )
  }
  throw new Error('Contract address should not be empty!')
}
Example #16
Source File: dsa.ts    From dsa-connect with MIT License 5 votes vote down vote up
/**
   * Build new DSA transactionConfiguration.
   *
   * @param {address} _d.authority (optional)
   * @param {address} _d.origin (optional)
   * @param {number|string} _d.gasPrice (optional) not optional in "node"
   * @param {number|string} _d.gas (optional) not optional in "node"
   * @param {number|string} _d.nonce (optional) not optional in "node"
   */
  async buildTransactionConfig(
    params: {
      authority?: string
      origin?: string
    } & Pick<TransactionConfig, 'from' | 'gasPrice' | 'gas' | 'nonce'>
  ) {
    const defaultAddress = await this.internal.getAddress()

    const defaults = {
      version: 2,
      origin: this.origin,
      authority: defaultAddress,
    }

    const mergedParams = Object.assign(defaults, params)

    if (!mergedParams.from) throw new Error(`Parameter 'from' is not defined.`)

    const to = Addresses.core[this.instance.chainId].index

    const contracts = new this.web3.eth.Contract(Abi.core.index, Addresses.core[this.instance.chainId].index)
    const data = contracts.methods.build(mergedParams.authority, mergedParams.version, mergedParams.origin).encodeABI()

    const transactionConfig = await this.internal.getTransactionConfig({
      from: mergedParams.from,
      to,
      data,
      gas: mergedParams.gas,
      gasPrice: mergedParams.gasPrice,
      nonce: mergedParams.nonce,
    })

    return transactionConfig
  }
Example #17
Source File: index.ts    From tatum-js with MIT License 5 votes vote down vote up
mintMultipleProvenanceSignedTransaction = async (
  body: ChainMintMultipleNft & { fixedValues: string[][] },
  web3: EvmBasedWeb3,
  provider?: string,
) => {
  const {
    fromPrivateKey,
    to,
    tokenId,
    contractAddress,
    url,
    nonce,
    signatureId,
    authorAddresses,
    cashbackValues,
    fixedValues,
    erc20,
    fee,
  } = body

  const client = await web3.getClient(provider, fromPrivateKey)

  const contract = new client.eth.Contract(Erc721_Provenance.abi as any, contractAddress)
  const cb: string[][] = []
  const fv: string[][] = []
  if (authorAddresses && cashbackValues && fixedValues) {
    for (let i = 0; i < cashbackValues.length; i++) {
      const cb2: string[] = []
      const fv2: string[] = []
      for (let j = 0; j < cashbackValues[i].length; j++) {
        cb2.push(`0x${new BigNumber(cashbackValues[i][j]).multipliedBy(100).toString(16)}`)
        fv2.push(`0x${new BigNumber(client.utils.toWei(fixedValues[i][j], 'ether')).toString(16)}`)
      }
      cb.push(cb2)
      fv.push(fv2)
    }
  }

  const tx: TransactionConfig = {
    from: undefined,
    to: contractAddress.trim(),
    data: erc20
      ? contract.methods
          .mintMultiple(
            to.map((t) => t.trim()),
            tokenId,
            url,
            authorAddresses ?? [],
            cb,
            fv,
            erc20,
          )
          .encodeABI()
      : contract.methods.mintMultiple(to, tokenId, url, authorAddresses ?? [], cb, fv).encodeABI(),
    nonce,
  }
  return await evmBasedUtils.prepareSignedTransactionAbstraction(
    client,
    tx,
    web3,
    signatureId,
    fromPrivateKey,
    fee?.gasLimit,
    fee?.gasPrice,
  )
}
Example #18
Source File: transaction.ts    From dsa-connect with MIT License 5 votes vote down vote up
/**
   * Send transaction and get transaction hash.
   */
  send = async (transactionConfig: TransactionConfig, transactionCallbacks: TransactionCallbacks = {}): Promise<string> => {
    return new Promise(async (resolve, reject)=>{
      if (transactionConfig.to == Addresses.genesis)
        throw Error(
          `Please configure the DSA instance by calling dsa.setInstance(dsaId). More details: https://docs.instadapp.io/setup`
        )

      if (this.dsa.config.mode == 'node') {
        
        const signedTransaction = await this.dsa.web3.eth.accounts.signTransaction(
          transactionConfig,
          this.dsa.config.privateKey
        )

        if (!signedTransaction.rawTransaction)
          throw new Error('Error while signing transaction. Please contact our support: https://docs.instadapp.io/')
        this.dsa.web3.eth.sendSignedTransaction(signedTransaction.rawTransaction).on("transactionHash", (txHash) => {
          resolve(txHash);
          return txHash;
        })
        .on("error", (error) => {
          reject(error);
          return;
        });
      } else {
        this.dsa.web3.eth.sendTransaction(transactionConfig).on("transactionHash", (txHash) => {
          resolve(txHash);
          return txHash;
        })
        .on("receipt", (receipt) => {
          transactionCallbacks.onReceipt && transactionCallbacks.onReceipt(receipt);
         })
        .on("confirmation", (confirmationNumber, receipt, latestBlockHash) => {
          transactionCallbacks.onConfirmation && transactionCallbacks.onConfirmation(confirmationNumber, receipt, latestBlockHash);
         })
        .on("error", (error) => {
          reject(error);
          return;
        });
      }
    })
  }
Example #19
Source File: evm-based.auction.ts    From tatum-js with MIT License 5 votes vote down vote up
createAuctionSignedTransaction = async (
  body: CreateAuction,
  web3: EvmBasedWeb3,
  provider?: string,
): Promise<string> => {
  const client = web3.getClient(provider)

  const params = [
    body.id,
    body.isErc721,
    body.nftAddress.trim(),
    `0x${new BigNumber(body.tokenId).toString(16)}`,
    body.seller.trim(),
    `0x${new BigNumber(body.amount || 0).toString(16)}`,
    `0x${new BigNumber(body.endedAt).toString(16)}`,
    body.erc20Address || '0x0000000000000000000000000000000000000000',
  ]
  body.amount = undefined

  const methodName = 'createAuction'
  const methodAbi = MarketplaceSmartContract.abi.find((a) => a.name === methodName)
  // TODO any type
  const contract = new client.eth.Contract([methodAbi as any])

  const tx: TransactionConfig = {
    from: 0,
    to: body.contractAddress.trim(),
    data: contract.methods[methodName as string](...params).encodeABI(),
    nonce: body.nonce,
  }

  return evmBasedUtils.prepareSignedTransactionAbstraction(
    client,
    tx,
    web3,
    body.signatureId,
    body.fromPrivateKey,
    body.fee?.gasLimit,
    body.fee?.gasPrice,
  )
}
Example #20
Source File: erc721.ts    From dsa-connect with MIT License 5 votes vote down vote up
/**
    * Approve
    */
   async approve(params: Erc721InputParams): Promise<string> {
    const txObj: TransactionConfig = await this.approveTxObj(params);
    
    return this.dsa.sendTransaction(txObj);
   }
Example #21
Source File: index.ts    From tatum-js with MIT License 5 votes vote down vote up
mintMultipleCashbackSignedTransaction = async (
  body: ChainMintMultipleNft,
  web3: EvmBasedWeb3,
  provider?: string,
) => {
  const {
    fromPrivateKey,
    to,
    tokenId,
    contractAddress,
    url,
    nonce,
    signatureId,
    authorAddresses,
    cashbackValues,
    fee,
    erc20,
  } = body

  const client = await web3.getClient(provider, fromPrivateKey)

  const contract = new client.eth.Contract(Erc721Token.abi as any, contractAddress)
  const cashbacks: string[][] = cashbackValues!
  const cb = cashbacks.map((cashback) =>
    cashback.map((c) => `0x${new BigNumber(client.utils.toWei(c, 'ether')).toString(16)}`),
  )

  const tx: TransactionConfig = {
    from: undefined,
    to: contractAddress.trim(),
    data: erc20
      ? contract.methods.mintMultipleCashback(to, tokenId, url, authorAddresses, cb, erc20).encodeABI()
      : contract.methods.mintMultipleCashback(to, tokenId, url, authorAddresses, cb).encodeABI(),
    nonce,
  }
  return await evmBasedUtils.prepareSignedTransactionAbstraction(
    client,
    tx,
    web3,
    signatureId,
    fromPrivateKey,
    fee?.gasLimit,
    fee?.gasPrice,
  )
}
Example #22
Source File: erc20.ts    From dsa-connect with MIT License 5 votes vote down vote up
/**
    * Transfer Tx object
    */
   async transferTxObj(params: Erc20InputParams): Promise<TransactionConfig> {
    if (!params.to) {
      params.to = this.dsa.instance.address;
    }

    if (params.to === Addresses.genesis) {
      throw new Error("'to' is not defined and instance is not set.")
    }

    if (!params.amount) {
      throw new Error("'amount' is not a number")
    }
    
    if(!params.from) {
      params.from = await this.dsa.internal.getAddress()
    }

    let txObj: TransactionConfig;

    if (["eth", TokenInfo.eth.address].includes(params.token.toLowerCase())) {
      if (["-1", this.dsa.maxValue].includes(params.amount)) {
        throw new Error("ETH amount value cannot be passed as '-1'.")
      }

      txObj = await this.dsa.internal.getTransactionConfig({
        from: params.from,
        to: params.to,
        data: "0x",
        gas: params.gas,
        gasPrice: params.gasPrice,
        nonce: params.nonce,
        value: params.amount,
      } as GetTransactionConfigParams)
    } else {
      const toAddr: string = params.to;
      params.to = this.dsa.internal.filterAddress(params.token)
      const contract: Contract = new this.dsa.web3.eth.Contract(Abi.basics.erc20, params.to)

      if (["-1", this.dsa.maxValue].includes(params.amount)) {
        await contract.methods
          .balanceOf(params.from)
          .call()
          .then((bal: any) => (params.amount = bal))
          .catch((err: any) => {
            throw new Error(`Error while getting token balance: ${err}`);
          });
      } else {
        params.amount = this.dsa.web3.utils.toBN(params.amount).toString()
      }
      const data: string = contract.methods
        .transfer(toAddr, params.amount)
        .encodeABI();

      txObj = await this.dsa.internal.getTransactionConfig({
        from: params.from,
        to: params.to,
        data: data,
        gas: params.gas,
        gasPrice: params.gasPrice,
        nonce: params.nonce,
        value: 0
      } as GetTransactionConfigParams);
    }

    return txObj;
   }