web3-eth-contract#Contract TypeScript Examples
The following examples show how to use
web3-eth-contract#Contract.
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: web3.service.ts From gnosis.1inch.exchange with MIT License | 6 votes |
public getInstance(abi: any[], address: string): Observable<Contract> {
return this.web3$.pipe(
map((web3) => {
// @ts-ignore
return (new web3.eth.Contract(
abi,
address
)) as Contract;
}),
);
}
Example #2
Source File: erc20.ts From dsa-connect with MIT License | 6 votes |
/**
* 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 #3
Source File: test-contract-variables.ts From moonbeam with GNU General Public License v3.0 | 6 votes |
describeDevMoonbeam("Block Contract - Block variables", (context) => {
let blockContract: Contract;
before("Setup: Creating contract with block variables", async function () {
const { contract, rawTx } = await createContract(context, "CheckBlockVariables");
await context.createBlock({ transactions: [rawTx] });
blockContract = contract;
});
it("should store the valid block number at creation", async function () {
expect(await blockContract.methods.initialnumber().call()).to.eq("1");
});
// TODO: Fix block number from contract call
it.skip("should return parent block number + 1 when accessed by RPC call", async function () {
const block = await context.web3.eth.getBlock("latest");
expect(await blockContract.methods.getNumber().call()).to.eq("1");
expect(await blockContract.methods.getNumber().call()).to.eq(block.number.toString());
});
it("should store the valid chain id at creation", async function () {
expect(await blockContract.methods.initialchainid().call()).to.equal("1281");
});
});
Example #4
Source File: SaffronContext.tsx From rari-dApp with GNU Affero General Public License v3.0 | 6 votes |
SaffronProvider = memo(({ children }) => {
const { rari } = useRari();
const [saffronStrategy, setSaffronStrategy] = useState(() => {
return new rari.web3.eth.Contract(
SaffronStrategyABI as any,
SaffronStrategyAddress
);
});
const [saffronPool, setSaffronPool] = useState(() => {
return new rari.web3.eth.Contract(
SaffronPoolABI as any,
SaffronPoolAddress
);
});
useEffect(() => {
setSaffronStrategy(
new rari.web3.eth.Contract(
SaffronStrategyABI as any,
SaffronStrategyAddress
)
);
setSaffronPool(
new rari.web3.eth.Contract(SaffronPoolABI as any, SaffronPoolAddress)
);
}, [rari]);
return (
<SaffronContext.Provider value={{ saffronStrategy, saffronPool }}>
{children}
</SaffronContext.Provider>
);
})
Example #5
Source File: index.ts From connect-wallet with MIT License | 6 votes |
/**
* Add contract to Web3 without providing contract name to initialize it, then you will
* able to use contract function to get contract from web3 and use contract methods.
*
* @param {INoNameContract} contract contract object with contract address and abi.
* @returns return contract web3 methods.
* @example connectWallet.getContract(contract);
*/
public getContract(contract: INoNameContract): Contract {
return new this.Web3.eth.Contract(contract.abi, contract.address);
}
Example #6
Source File: contractTypes.ts From webapp with MIT License | 6 votes |
buildContract = <T>(
abi: AbiItem[],
contractAddress?: string,
injectedWeb3?: Web3
): ContractTyped<T> =>
(contractAddress
? new (injectedWeb3 || web3).eth.Contract(abi, contractAddress)
: new (injectedWeb3 || web3).eth.Contract(
abi
)) as unknown as ContractTyped<T>
Example #7
Source File: useAllowance.ts From PolkaBridge-Farming with MIT License | 6 votes |
useAllowance = (lpContract: Contract) => {
const [allowance, setAllowance] = useState(new BigNumber(0))
const { account }: { account: string; ethereum: provider } = useWallet()
const pbr = usePolkaBridge()
const masterChefContract = getMasterChefContract(pbr)
const fetchAllowance = useCallback(async () => {
const allowance = await getAllowance(
lpContract,
masterChefContract,
account,
)
setAllowance(new BigNumber(allowance))
}, [account, masterChefContract, lpContract])
useEffect(() => {
if (account && masterChefContract && lpContract) {
fetchAllowance()
}
let refreshInterval = setInterval(fetchAllowance, 10000)
return () => clearInterval(refreshInterval)
}, [account, masterChefContract, lpContract])
return allowance
}
Example #8
Source File: erc20.ts From polkabridge-launchpad with MIT License | 6 votes |
getAllowance = async (
lpContract: Contract,
masterChefContract: Contract,
account: string,
): Promise<string> => {
try {
const allowance: string = await lpContract.methods
.allowance(account, masterChefContract.options.address)
.call()
return allowance
} catch (e) {
return '0'
}
}
Example #9
Source File: Multicall.ts From web3-multicall with MIT License | 6 votes |
constructor({ chainId, provider, multicallAddress }: ConstructorArgs) {
this.web3 = new Web3(provider);
const _multicallAddress = multicallAddress
? multicallAddress
: chainId
? CHAIN_ID_TO_MULTICALL_ADDRESS[chainId]
: undefined;
if (!_multicallAddress) {
throw new Error(
'No address found via chainId. Please specify multicallAddress.'
);
}
this.multicall = new this.web3.eth.Contract(
mulitcallAbi as AbiItem[],
_multicallAddress
);
}
Example #10
Source File: Contracts.ts From perpetual with Apache License 2.0 | 6 votes |
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 #11
Source File: exchange.ts From lp-inspector with MIT License | 6 votes |
async getReserves(tokenA: string, tokenB: string) {
if (!this.exchangeFactoryAddress) {
this.exchangeFactoryAddress = await this.exchangeContract.methods
.factory()
.call();
}
const factory = new this.web3.eth.Contract(
factoryAbi,
this.exchangeFactoryAddress
);
const pair = await factory.methods.getPair(tokenA, tokenB).call();
const pairContract = new this.web3.eth.Contract(pairAbi, pair);
const {
"0": reserveTokenA,
"1": reserveTokenB,
} = await pairContract.methods.getReserves().call();
const token0 = await pairContract.methods
.token0()
.call()
.then((token: string) => token.toLowerCase());
return [
token0 === tokenA ? reserveTokenA : reserveTokenB,
token0 === tokenA ? reserveTokenB : reserveTokenA,
];
}
Example #12
Source File: useAllowance.ts From frontend-ui with GNU General Public License v3.0 | 6 votes |
useIfoAllowance = (tokenContract: Contract, spenderAddress: string, dependency?: any) => {
const { account }: { account: string } = useWallet()
const [allowance, setAllowance] = useState(null)
useEffect(() => {
const fetch = async () => {
try {
const res = await tokenContract.methods.allowance(account, spenderAddress).call()
setAllowance(new BigNumber(res))
} catch (e) {
setAllowance(null)
}
}
fetch()
}, [account, spenderAddress, tokenContract, dependency])
return allowance
}
Example #13
Source File: v1.ts From ethereum-sdk with MIT License | 6 votes |
export async function deployErc721V1(web3: Web3, name: string, symbol: string): Promise<Contract> {
const empty = new web3.eth.Contract(erc721v1Abi)
const [address] = await web3.eth.getAccounts()
const deploy = await empty.deploy({
data: erc721v1MintableTokenBytecode,
arguments: [
name,
symbol,
"https://api-test.rarible.com/contractMetadata/{address}",
"ipfs:/",
"0x002ed05478c75974e08f0811517aa0e3eddc1380",
],
})
return deploy.send({ from: address, gas: 4000000, gasPrice: "0" })
}
Example #14
Source File: useAllowance.ts From luaswap-interface with GNU General Public License v3.0 | 6 votes |
useAllowance = (lpContract: Contract) => {
const [allowance, setAllowance] = useState(new BigNumber(0))
const { account } = useWeb3React()
const sushi = useSushi()
const masterChefContract = getMasterChefContract(sushi)
const fetchAllowance = useCallback(async () => {
const allowance = await getAllowance(
lpContract,
masterChefContract,
// @ts-ignore
account
)
setAllowance(new BigNumber(allowance))
}, [account, masterChefContract, lpContract])
useEffect(() => {
if (account && masterChefContract && lpContract) {
fetchAllowance()
}
const refreshInterval = setInterval(fetchAllowance, 10000)
return () => clearInterval(refreshInterval)
}, [account, masterChefContract, lpContract])
return allowance
}
Example #15
Source File: contract.ts From waifusion-site with MIT License | 6 votes |
// Contracts
getDungeonContract = async (): Promise<Contract> => {
return new (window as any).web3.eth.Contract(
this.globals?.network === Network.BSC ? dungeonBscAbi : dungeonAbi,
this.globals?.dungeonAddress,
{
from: this.address,
}
);
};
Example #16
Source File: web3.service.ts From gnosis.1inch.exchange with MIT License | 5 votes |
public getInstanceWithoutNetwork(abi: any[]): Contract {
const web3 = new Web3('');
// @ts-ignore
return new web3.eth.Contract(abi) as Contract;
}
Example #17
Source File: erc20.ts From dsa-connect with MIT License | 5 votes |
/**
* 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;
}
Example #18
Source File: test-contract-delegate-call.ts From moonbeam with GNU General Public License v3.0 | 5 votes |
describeDevMoonbeam("DELEGATECALL for precompiles", (context) => {
let contractProxy: Contract;
let proxyInterface: ethers.utils.Interface;
const PRECOMPILE_PREFIXES = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 1024, 1025, 1026, 2048, 2049, 2050, 2051, 2052, 2053, 2054, 2055,
];
// Ethereum precompile 1-9 are pure and allowed to be called through DELEGATECALL
const ALLOWED_PRECOMPILE_PREFIXES = PRECOMPILE_PREFIXES.filter((add) => add <= 9);
const FORBIDDEN_PRECOMPILE_PREFIXES = PRECOMPILE_PREFIXES.filter((add) => add > 9);
const DELEGATECALL_FORDIDDEN_MESSAGE =
"0x0000000000000000000000000000000000000000000000000000000000000000" +
"0000000000000000000000000000000000000000000000000000000000000040" +
"000000000000000000000000000000000000000000000000000000000000002e" +
"63616e6e6f742062652063616c6c656420" + // cannot be called
"776974682044454c454741544543414c4c20" + // with DELEGATECALL
"6f722043414c4c434f4445" + // or CALLCODE
"000000000000000000000000000000000000"; // padding
before("Setup delecateCall contract", async () => {
const contractDetails = await createContract(context, "TestCallList");
contractProxy = contractDetails.contract;
await context.createBlock({ transactions: [contractDetails.rawTx] });
proxyInterface = new ethers.utils.Interface((await getCompiled("TestCallList")).contract.abi);
});
for (const precompilePrefix of ALLOWED_PRECOMPILE_PREFIXES) {
it(`should succeed for standard precompile ${precompilePrefix}`, async function () {
const precompileAddress = `0x${precompilePrefix.toString(16).padStart(40, "0")}`;
const tx_call = await customWeb3Request(context.web3, "eth_call", [
{
from: GENESIS_ACCOUNT,
to: contractProxy.options.address,
gas: "0x200000",
value: "0x00",
data: proxyInterface.encodeFunctionData("delegateCall", [precompileAddress, "0x00"]),
},
]);
expect(tx_call.result).to.not.equal(DELEGATECALL_FORDIDDEN_MESSAGE);
});
}
for (const precompilePrefix of FORBIDDEN_PRECOMPILE_PREFIXES) {
it(`should fail for non-standard precompile ${precompilePrefix}`, async function () {
const precompileAddress = `0x${precompilePrefix.toString(16).padStart(40, "0")}`;
const tx_call = await customWeb3Request(context.web3, "eth_call", [
{
from: GENESIS_ACCOUNT,
to: contractProxy.options.address,
gas: "0x100000",
value: "0x00",
data: proxyInterface.encodeFunctionData("delegateCall", [precompileAddress, "0x00"]),
},
]);
expect(tx_call.result).to.equal(DELEGATECALL_FORDIDDEN_MESSAGE);
});
}
});
Example #19
Source File: createComptroller.ts From rari-dApp with GNU Affero General Public License v3.0 | 5 votes |
createERC20 = (fuse: Fuse, cTokenAddress: string) => {
const erc20 = new fuse.web3.eth.Contract(ERC20ABI as any, cTokenAddress);
return erc20;
}
Example #20
Source File: index.ts From connect-wallet with MIT License | 5 votes |
/**
* Get contract by providing contract name. If you don't have contracts use addContract function to initialize it.
*
* @param {String} name contract name.
* @returns return contract parameters and methods.
* @example connectWallet.Contract(ContractName);
*/
public Contract = (name: string): ContractWeb3 => this.contracts[name];
Example #21
Source File: getMiniChefApys.ts From beefy-api with MIT License | 5 votes |
getFarmApys = async (params: MiniChefApyParams) => {
const { web3, pools, minichefConfig, rewarderConfig } = params;
const apys = [];
// minichef
const minichefContract = getContractWithProvider(
minichefConfig.minichefAbi as any,
minichefConfig.minichef,
web3
);
const miniChefTokenPerSecond = new BigNumber(
await minichefContract.methods[minichefConfig.tokenPerSecondContractMethodName]().call()
);
const miniChefTotalAllocPoint = new BigNumber(
await minichefContract.methods.totalAllocPoint().call()
);
const miniChefTokenPrice = await fetchPrice({ oracle, id: minichefConfig.outputOracleId });
// rewarder, if rewarder is set
let rewarderContract: Contract | undefined = undefined;
let rewarderTokenPerSecond: BigNumber | undefined;
let rewarderTokenPrice: number | undefined;
if (rewarderConfig) {
rewarderContract = getContractWithProvider(
SushiComplexRewarderTime as any,
rewarderConfig.rewarder,
web3
);
rewarderTokenPerSecond = new BigNumber(await rewarderContract.methods.rewardPerSecond().call());
rewarderTokenPrice = await fetchPrice({
oracle,
id: rewarderConfig.rewarderTokenOracleId,
});
}
const { balances, allocPoints, rewardAllocPoints } = await getPoolsData(params);
// get apy for each pool
for (let i = 0; i < pools.length; i++) {
const pool = pools[i];
const lpPrice = await fetchPrice({ oracle: 'lps', id: pool.name });
const totalStakedInUsd = balances[i].times(lpPrice).dividedBy('1e18');
let totalYearlyRewardsInUsd: BigNumber = new BigNumber(0);
// MiniChef rewards
const miniChefPoolBlockRewards = miniChefTokenPerSecond
.times(allocPoints[i])
.dividedBy(miniChefTotalAllocPoint);
const miniChefYearlyRewards = miniChefPoolBlockRewards
.dividedBy(secondsPerBlock)
.times(secondsPerYear);
const miniChefYearlyRewardsInUsd = miniChefYearlyRewards
.times(miniChefTokenPrice)
.dividedBy(DECIMALS);
totalYearlyRewardsInUsd = totalYearlyRewardsInUsd.plus(miniChefYearlyRewardsInUsd);
// Rewarder rewards, if rewarder is set
if (rewarderConfig) {
const allocPoint = rewardAllocPoints[i];
const nativeRewards = rewarderTokenPerSecond
.times(allocPoint)
.dividedBy(rewarderConfig.rewarderTotalAllocPoint);
const yearlyNativeRewards = nativeRewards.dividedBy(secondsPerBlock).times(secondsPerYear);
const nativeRewardsInUsd = yearlyNativeRewards.times(rewarderTokenPrice).dividedBy(DECIMALS);
totalYearlyRewardsInUsd = totalYearlyRewardsInUsd.plus(nativeRewardsInUsd);
}
const apy = totalYearlyRewardsInUsd.dividedBy(totalStakedInUsd);
apys.push(apy);
}
return apys;
}
Example #22
Source File: contracthelper.ts From crypto-capsule with MIT License | 5 votes |
getCapsuleContract = async (): Promise<Contract> => {
const globals = await getGlobals();
return new (window as any).web3.eth.Contract(capsuleAbi, globals.CAPSULE, {
from: await getAddress(),
});
}
Example #23
Source File: useAllStakedValue.ts From PolkaBridge-Farming with MIT License | 5 votes |
useAllStakedValue = () => {
const [balances, setBalance] = useState<Array<StakedValue>>([])
const pbr = usePolkaBridge()
const farms = getFarms(pbr)
const pbrPrice = usePBRPrice()
const masterChefContract = getMasterChefContract(pbr)
//console.log('pbrPrice: ', pbrPrice.toString())
const fetchAllStakedValue = useCallback(async () => {
const balances: Array<StakedValue> = await Promise.all(
farms.map(
({
pid,
lpContract,
tokenContract,
token2Contract,
tokenSymbol,
token2Symbol,
isActived,
poolWeight
}: {
pid: number
lpContract: Contract
tokenContract: Contract
token2Contract: Contract,
tokenSymbol: any
token2Symbol: any,
isActived: any,
poolWeight: BigNumber
}) =>
getLPValue(
masterChefContract,
lpContract,
tokenContract,
token2Contract,
pid,
pbrPrice,
tokenSymbol,
token2Symbol,
isActived,
poolWeight
)
),
)
setBalance(balances)
}, [masterChefContract, pbr, pbrPrice])
useEffect(() => {
if (masterChefContract && pbr && pbrPrice) {
fetchAllStakedValue()
}
}, [masterChefContract, setBalance, pbr, pbrPrice])
return balances
}
Example #24
Source File: erc20.ts From polkabridge-launchpad with MIT License | 5 votes |
getContract = (provider: any, address: string) => {
const web3 = new Web3((provider as any) || config.ankrEthereumRpc)
const contract = new web3.eth.Contract(
ERC20ABI.abi as unknown as AbiItem,
address,
)
return contract
}
Example #25
Source File: Multicall.ts From web3-multicall with MIT License | 5 votes |
multicall: Contract;
Example #26
Source File: Admin.ts From perpetual with Apache License 2.0 | 5 votes |
private perpetual: Contract;