@ethersproject/providers#StaticJsonRpcProvider TypeScript Examples
The following examples show how to use
@ethersproject/providers#StaticJsonRpcProvider.
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: realityETH.ts From snapshot-plugins with MIT License | 6 votes |
retrieveInfoFromOracle = async (
provider: StaticJsonRpcProvider,
network: string,
oracleAddress: string,
questionId: string | undefined
): Promise<{
currentBond: BigNumber | undefined;
isApproved: boolean;
endTime: number | undefined;
}> => {
if (questionId) {
const result = await multicall(network, provider, ORACLE_ABI, [
[oracleAddress, 'getFinalizeTS', [questionId]],
[oracleAddress, 'getBond', [questionId]],
[oracleAddress, 'getBestAnswer', [questionId]]
]);
const currentBond = BigNumber.from(result[1][0]);
const answer = BigNumber.from(result[2][0]);
return {
currentBond,
isApproved: answer.eq(BigNumber.from(1)),
endTime: BigNumber.from(result[0][0]).toNumber()
};
}
return {
currentBond: undefined,
isApproved: false,
endTime: undefined
};
}
Example #2
Source File: lp-bond.ts From rugenerous-frontend with MIT License | 6 votes |
async getTreasuryBalance(networkID: Networks, provider: StaticJsonRpcProvider) {
const addresses = getAddresses(networkID);
const token = this.getContractForReserve(networkID, provider);
const tokenAddress = this.getAddressForReserve(networkID);
const bondCalculator = getBondCalculator(networkID, provider, this.name);
const tokenAmount = await token.balanceOf(addresses.TREASURY_ADDRESS);
const valuation = await bondCalculator.valuation(tokenAddress, tokenAmount);
const markdown = await bondCalculator.markdown(tokenAddress);
const token1: string = await token.token1();
const token1Contract = new ethers.Contract(token1, ERC20Contract, provider);
const token1Decimals = await token1Contract.decimals();
const token0: string = await token.token0();
const token0Contract = new ethers.Contract(token0, ERC20Contract, provider);
const token0Decimals = await token0Contract.decimals();
const isRug = token1.toLowerCase() === addresses.RUG_ADDRESS.toLowerCase();
var tokenUSD;
if (isRug) {
tokenUSD = (valuation / Math.pow(10, 9)) * (markdown / Math.pow(10, token0Decimals));
} else {
tokenUSD = (valuation / Math.pow(10, 9)) * (markdown / Math.pow(10, token1Decimals));
}
return tokenUSD;
}
Example #3
Source File: lp-bond.ts From wonderland-frontend with MIT License | 6 votes |
async getTreasuryBalance(networkID: Networks, provider: StaticJsonRpcProvider) {
const addresses = getAddresses(networkID);
const token = this.getContractForReserve(networkID, provider);
const tokenAddress = this.getAddressForReserve(networkID);
const bondCalculator = getBondCalculator(networkID, provider);
const tokenAmount = await token.balanceOf(addresses.TREASURY_ADDRESS);
const valuation = await bondCalculator.valuation(tokenAddress, tokenAmount);
const markdown = await bondCalculator.markdown(tokenAddress);
const tokenUSD = (valuation / Math.pow(10, 9)) * (markdown / Math.pow(10, 18));
return tokenUSD;
}
Example #4
Source File: get-treasury.ts From rugenerous-frontend with MIT License | 6 votes |
async function getBalance(networkID: Networks, provider: StaticJsonRpcProvider, token: IToken) {
const addresses = getAddresses(networkID);
const tokenContract = new ethers.Contract(token.address, ERC20Contract, provider);
let tokenAmount = 0;
if (tokenContract.balanceOf) {
tokenAmount = await tokenContract.balanceOf(addresses.TREASURY_ADDRESS);
}
const tokenDecimals = await tokenContract.decimals();
return tokenAmount / Math.pow(10, tokenDecimals);
}
Example #5
Source File: realityModule.ts From snapshot-plugins with MIT License | 6 votes |
getProposalDetails = async (
provider: StaticJsonRpcProvider,
network: string,
moduleAddress: string,
questionHash: string,
txHashes: string[]
): Promise<{ questionId: string; nextTxIndex: number | undefined }> => {
const proposalInfo = (
await multicall(
network,
provider,
REALITY_MODULE_ABI,
[[moduleAddress, 'questionIds', [questionHash]]].concat(
txHashes.map((txHash) => [
moduleAddress,
'executedProposalTransactions',
[questionHash, txHash]
])
)
)
).map((res) => res[0]);
const questionId = proposalInfo[0];
// We need to offset the index by -1 the first element is the questionId
const nextIndexToExecute = proposalInfo.indexOf(false, 1) - 1;
return {
questionId: questionId !== HashZero ? questionId : undefined,
nextTxIndex:
nextIndexToExecute < 0 || nextIndexToExecute >= txHashes.length
? undefined
: nextIndexToExecute
};
}
Example #6
Source File: index.ts From snapshot-strategies with MIT License | 6 votes |
/**
* CityDAO Square Root Snapshot Strategy
* @version 0.0.1
* @summary Holders of an ERC1155 token can cast a number of votes equal to the square root of their net token holdings.
* @see https://archive.ph/beczV
* @author Will Holley <https://721.dev>
*/
async function strategy(
space: string,
network: string,
provider: StaticJsonRpcProvider,
addresses: Array<string>,
params: Params,
snapshot: number
): Promise<ScoresByAddress> {
// Query default scores.
const scores: ScoresByAddress = await erc1155BalanceOfStrategy(
space,
network,
provider,
addresses,
params,
snapshot
);
// Support Plural Voting
const magnitude = params.voiceCredits || 1;
// Update in place, rounding down.
for (const address in scores) {
scores[address] = Math.floor(Math.sqrt(scores[address] * magnitude));
}
return scores;
}
Example #7
Source File: eip1271.ts From snapshot.js with MIT License | 6 votes |
export async function verifyDefault(
address: string,
sig: string,
hash: string,
provider: StaticJsonRpcProvider
) {
let returnValue;
const magicValue = '0x1626ba7e';
const abi =
'function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4 magicValue)';
try {
returnValue = await call(
provider,
[abi],
[address, 'isValidSignature', [arrayify(hash), sig]]
);
} catch (e) {
console.log(e);
return false;
}
return returnValue.toLowerCase() === magicValue.toLowerCase();
}
Example #8
Source File: lp-bond.ts From lobis-frontend with MIT License | 6 votes |
constructor(customBondOpts: CustomLPBondOpts) {
super(customBondOpts);
this.getTreasuryBalance = async (networkID: Networks, provider: StaticJsonRpcProvider) => {
const tokenAmount = await super.getTreasuryBalance(networkID, provider);
const tokenPrice = this.getTokenPrice();
return tokenAmount * tokenPrice;
};
this.getTokenAmount = async (networkID: Networks, provider: StaticJsonRpcProvider) => {
const tokenAmount = await super.getTokenAmount(networkID, provider);
const tokenPrice = this.getTokenPrice();
return tokenAmount * tokenPrice;
};
}
Example #9
Source File: bond.ts From rugenerous-frontend with MIT License | 5 votes |
public getContractForTreasury(networkID: Networks, provider: StaticJsonRpcProvider | JsonRpcSigner) {
const treasuryAddress = getAddresses(networkID).TREASURY_ADDRESS;
return new Contract(treasuryAddress, TreasuryContract, provider);
}
Example #10
Source File: stable-bond.ts From lobis-frontend with MIT License | 5 votes |
public getLobiAmount(networkID: Networks, provider: StaticJsonRpcProvider) {
return new Promise<number>(reserve => reserve(0));
}
Example #11
Source File: stable-bond.ts From wonderland-frontend with MIT License | 5 votes |
public async getTokenAmount(networkID: Networks, provider: StaticJsonRpcProvider) {
return this.getTreasuryBalance(networkID, provider);
}
Example #12
Source File: stable-bond.ts From lobis-frontend with MIT License | 5 votes |
public async getTokenAmount(networkID: Networks, provider: StaticJsonRpcProvider) {
return this.getTreasuryBalance(networkID, provider);
}
Example #13
Source File: bond-calculator.ts From wonderland-frontend with MIT License | 5 votes |
export function getBondCalculator(networkID: Networks, provider: StaticJsonRpcProvider) {
const addresses = getAddresses(networkID);
return new ethers.Contract(addresses.TIME_BONDING_CALC_ADDRESS, BondingCalcContract, provider);
}
Example #14
Source File: index.ts From snapshot-plugins with MIT License | 5 votes |
async getExecutionDetailsWithHashes(
network: string,
moduleAddress: string,
proposalId: string,
txHashes: string[]
): Promise<Omit<ProposalDetails, 'transactions'>> {
const provider: StaticJsonRpcProvider = getProvider(network);
const question = await buildQuestion(proposalId, txHashes);
const questionHash = solidityKeccak256(['string'], [question]);
const proposalDetails = await getProposalDetails(
provider,
network,
moduleAddress,
questionHash,
txHashes
);
const moduleDetails = await getModuleDetails(
provider,
network,
moduleAddress
);
const questionState = await checkPossibleExecution(
provider,
network,
moduleDetails.oracle,
proposalDetails.questionId
);
const infoFromOracle = await retrieveInfoFromOracle(
provider,
network,
moduleDetails.oracle,
proposalDetails.questionId
);
return {
...moduleDetails,
proposalId,
...questionState,
...proposalDetails,
txHashes,
...infoFromOracle
};
}
Example #15
Source File: multicaller.ts From snapshot.js with MIT License | 5 votes |
public provider: StaticJsonRpcProvider;
Example #16
Source File: bond.ts From lobis-frontend with MIT License | 5 votes |
public abstract getTokenAmount(networkID: Networks, provider: StaticJsonRpcProvider): Promise<number>;
Example #17
Source File: lp-bond.ts From wonderland-frontend with MIT License | 5 votes |
public getTimeAmount(networkID: Networks, provider: StaticJsonRpcProvider) {
return this.getReserves(networkID, provider, false);
}
Example #18
Source File: lp-bond.ts From rugenerous-frontend with MIT License | 5 votes |
public getTokenAmount(networkID: Networks, provider: StaticJsonRpcProvider) {
return this.getReserves(networkID, provider, true);
}
Example #19
Source File: bond.ts From lobis-frontend with MIT License | 5 votes |
// Async method that returns a Promise
public abstract getTreasuryBalance(networkID: Networks, provider: StaticJsonRpcProvider): Promise<number>;
Example #20
Source File: bond.ts From wonderland-frontend with MIT License | 5 votes |
// Async method that returns a Promise
public abstract getTreasuryBalance(networkID: Networks, provider: StaticJsonRpcProvider): Promise<number>;
Example #21
Source File: bond.ts From rugenerous-frontend with MIT License | 5 votes |
// Async method that returns a Promise
public abstract getTreasuryBalance(networkID: Networks, provider: StaticJsonRpcProvider): Promise<number>;
Example #22
Source File: lp-bond.ts From wonderland-frontend with MIT License | 5 votes |
public getTokenAmount(networkID: Networks, provider: StaticJsonRpcProvider) {
return this.getReserves(networkID, provider, true);
}
Example #23
Source File: web3-context.tsx From rugenerous-frontend with MIT License | 4 votes |
Web3ContextProvider: React.FC<{ children: ReactElement }> = ({ children }) => {
const dispatch = useDispatch();
const [connected, setConnected] = useState(false);
const [chainID, setChainID] = useState(DEFAULD_NETWORK);
const [providerChainID, setProviderChainID] = useState(DEFAULD_NETWORK);
const [address, setAddress] = useState("");
const [uri, setUri] = useState(getMainnetURI());
const [provider, setProvider] = useState<JsonRpcProvider>(new StaticJsonRpcProvider(uri));
const [web3Modal] = useState<Web3Modal>(
new Web3Modal({
cacheProvider: true,
providerOptions: {
walletconnect: {
package: WalletConnectProvider,
options: {
rpc: {
[Networks.AVAX]: getMainnetURI(),
},
},
},
},
}),
);
const hasCachedProvider = (): boolean => {
if (!web3Modal) return false;
if (!web3Modal.cachedProvider) return false;
return true;
};
const _initListeners = useCallback(
(rawProvider: JsonRpcProvider) => {
if (!rawProvider.on) {
return;
}
rawProvider.on("accountsChanged", () => setTimeout(() => window.location.reload(), 1));
rawProvider.on("chainChanged", async (chain: number) => {
changeNetwork(chain);
});
rawProvider.on("network", (_newNetwork, oldNetwork) => {
if (!oldNetwork) return;
window.location.reload();
});
},
[provider],
);
const changeNetwork = async (otherChainID: number) => {
const network = Number(otherChainID);
setProviderChainID(network);
};
const connect = useCallback(async () => {
const rawProvider = await web3Modal.connect();
_initListeners(rawProvider);
const connectedProvider = new Web3Provider(rawProvider, "any");
const chainId = await connectedProvider.getNetwork().then(network => Number(network.chainId));
const connectedAddress = await connectedProvider.getSigner().getAddress();
setAddress(connectedAddress);
setProviderChainID(chainId);
if (chainId === Networks.AVAX) {
setProvider(connectedProvider);
}
setConnected(true);
return connectedProvider;
}, [provider, web3Modal, connected]);
const checkWrongNetwork = async (): Promise<boolean> => {
if (providerChainID !== DEFAULD_NETWORK) {
const shouldSwitch = window.confirm(messages.switch_to_avalanche);
if (shouldSwitch) {
await swithNetwork();
window.location.reload();
}
return true;
}
return false;
};
const disconnect = useCallback(async () => {
web3Modal.clearCachedProvider();
setConnected(false);
setTimeout(() => {
window.location.reload();
}, 1);
}, [provider, web3Modal, connected]);
const onChainProvider = useMemo(
() => ({
connect,
disconnect,
hasCachedProvider,
provider,
connected,
address,
chainID,
web3Modal,
providerChainID,
checkWrongNetwork,
}),
[connect, disconnect, hasCachedProvider, provider, connected, address, chainID, web3Modal, providerChainID],
);
//@ts-ignore
return <Web3Context.Provider value={{ onChainProvider }}>{children}</Web3Context.Provider>;
}
Example #24
Source File: index.ts From snapshot-plugins with MIT License | 4 votes |
async loadClaimBondData(
web3: any,
network: string,
questionId: string,
oracleAddress: string
) {
const contract = new Contract(oracleAddress, ORACLE_ABI, web3);
const provider: StaticJsonRpcProvider = getProvider(network);
const account = (await web3.listAccounts())[0];
const [
[userBalance],
[bestAnswer],
[historyHash],
[isFinalized]
] = await multicall(network, provider, ORACLE_ABI, [
[oracleAddress, 'balanceOf', [account]],
[oracleAddress, 'getBestAnswer', [questionId]],
[oracleAddress, 'getHistoryHash', [questionId]],
[oracleAddress, 'isFinalized', [questionId]]
]);
let tokenSymbol = 'ETH';
let tokenDecimals = 18;
try {
const token = await call(provider, ORACLE_ABI, [
oracleAddress,
'token',
[]
]);
const [[symbol], [decimals]] = await multicall(
network,
provider,
ERC20_ABI,
[
[token, 'symbol', []],
[token, 'decimals', []]
]
);
tokenSymbol = symbol;
tokenDecimals = decimals;
} catch (e) {}
const answersFilter = contract.filters.LogNewAnswer(null, questionId);
const events = await contract.queryFilter(
answersFilter,
START_BLOCKS[network]
);
const users: Result[] = [];
const historyHashes: Result[] = [];
const bonds: Result[] = [];
const answers: Result[] = [];
// We need to send the information from last to first
events.reverse().forEach(({ args }) => {
users.push(args?.user.toLowerCase());
historyHashes.push(args?.history_hash);
bonds.push(args?.bond);
answers.push(args?.answer);
});
const alreadyClaimed = BigNumber.from(historyHash).eq(0);
const address = account.toLowerCase();
// Check if current user has submitted an answer
const currentUserAnswers = users.map((user, i) => {
if (user === address) return answers[i];
});
// If the user has answers, check if one of them is the winner
const votedForCorrectQuestion =
currentUserAnswers.some((answer) => {
if (answer) {
return BigNumber.from(answer).eq(bestAnswer);
}
}) && isFinalized;
// If user has balance in the contract, he should be able to withdraw
const hasBalance = !userBalance.eq(0) && isFinalized;
// Remove the first history and add an empty one
// More info: https://github.com/realitio/realitio-contracts/blob/master/truffle/contracts/Realitio.sol#L502
historyHashes.shift();
const firstHash = '0x0000000000000000000000000000000000000000000000000000000000000000' as unknown;
historyHashes.push(firstHash as Result);
return {
tokenSymbol,
tokenDecimals,
canClaim: (!alreadyClaimed && votedForCorrectQuestion) || hasBalance,
data: {
length: [bonds.length.toString()],
historyHashes,
users,
bonds,
answers
}
};
}
Example #25
Source File: web3-context.tsx From wonderland-frontend with MIT License | 4 votes |
Web3ContextProvider: React.FC<{ children: ReactElement }> = ({ children }) => {
const dispatch = useDispatch();
const [connected, setConnected] = useState(false);
const [chainID, setChainID] = useState(DEFAULD_NETWORK);
const [providerChainID, setProviderChainID] = useState(DEFAULD_NETWORK);
const [address, setAddress] = useState("");
const [uri, setUri] = useState(getMainnetURI());
const [provider, setProvider] = useState<JsonRpcProvider>(new StaticJsonRpcProvider(uri));
const [web3Modal] = useState<Web3Modal>(
new Web3Modal({
cacheProvider: true,
providerOptions: {
walletconnect: {
package: WalletConnectProvider,
options: {
rpc: {
[Networks.AVAX]: getMainnetURI(),
},
},
},
},
}),
);
const hasCachedProvider = (): boolean => {
if (!web3Modal) return false;
if (!web3Modal.cachedProvider) return false;
return true;
};
const _initListeners = useCallback(
(rawProvider: JsonRpcProvider) => {
if (!rawProvider.on) {
return;
}
rawProvider.on("accountsChanged", () => setTimeout(() => window.location.reload(), 1));
rawProvider.on("chainChanged", async (chain: number) => {
changeNetwork(chain);
});
rawProvider.on("network", (_newNetwork, oldNetwork) => {
if (!oldNetwork) return;
window.location.reload();
});
},
[provider],
);
const changeNetwork = async (otherChainID: number) => {
const network = Number(otherChainID);
setProviderChainID(network);
};
const connect = useCallback(async () => {
const rawProvider = await web3Modal.connect();
_initListeners(rawProvider);
const connectedProvider = new Web3Provider(rawProvider, "any");
const chainId = await connectedProvider.getNetwork().then(network => Number(network.chainId));
const connectedAddress = await connectedProvider.getSigner().getAddress();
setAddress(connectedAddress);
setProviderChainID(chainId);
if (chainId === Networks.AVAX) {
setProvider(connectedProvider);
}
setConnected(true);
return connectedProvider;
}, [provider, web3Modal, connected]);
const checkWrongNetwork = async (): Promise<boolean> => {
if (providerChainID !== DEFAULD_NETWORK) {
const shouldSwitch = window.confirm(messages.switch_to_avalanche);
if (shouldSwitch) {
await swithNetwork();
window.location.reload();
}
return true;
}
return false;
};
const disconnect = useCallback(async () => {
web3Modal.clearCachedProvider();
setConnected(false);
setTimeout(() => {
window.location.reload();
}, 1);
}, [provider, web3Modal, connected]);
const onChainProvider = useMemo(
() => ({
connect,
disconnect,
hasCachedProvider,
provider,
connected,
address,
chainID,
web3Modal,
providerChainID,
checkWrongNetwork,
}),
[connect, disconnect, hasCachedProvider, provider, connected, address, chainID, web3Modal, providerChainID],
);
//@ts-ignore
return <Web3Context.Provider value={{ onChainProvider }}>{children}</Web3Context.Provider>;
}
Example #26
Source File: web3-context.tsx From lobis-frontend with MIT License | 4 votes |
Web3ContextProvider: React.FC<{ children: ReactElement }> = ({ children }) => {
const dispatch = useDispatch();
const [connected, setConnected] = useState(false);
const [chainID, setChainID] = useState(DEFAULD_NETWORK);
const [providerChainID, setProviderChainID] = useState(DEFAULD_NETWORK);
const [address, setAddress] = useState("");
const [uri, setUri] = useState(getMainnetURI());
const [provider, setProvider] = useState<JsonRpcProvider>(new StaticJsonRpcProvider(uri));
const [web3Modal] = useState<Web3Modal>(
new Web3Modal({
cacheProvider: true,
providerOptions: {
walletconnect: {
package: WalletConnectProvider,
options: {
rpc: {
[Networks.MAINNET]: getMainnetURI(),
},
},
},
},
}),
);
const hasCachedProvider = (): boolean => {
if (!web3Modal) return false;
if (!web3Modal.cachedProvider) return false;
return true;
};
const _initListeners = useCallback(
(rawProvider: JsonRpcProvider) => {
if (!rawProvider.on) {
return;
}
rawProvider.on("accountsChanged", () => setTimeout(() => window.location.reload(), 1));
rawProvider.on("chainChanged", async (chain: number) => {
changeNetwork(chain);
});
rawProvider.on("network", (_newNetwork, oldNetwork) => {
if (!oldNetwork) return;
window.location.reload();
});
},
[provider],
);
const changeNetwork = async (otherChainID: number) => {
const network = Number(otherChainID);
setProviderChainID(network);
};
const connect = useCallback(async () => {
const rawProvider = await web3Modal.connect();
_initListeners(rawProvider);
const connectedProvider = new Web3Provider(rawProvider, "any");
const chainId = await connectedProvider.getNetwork().then(network => Number(network.chainId));
const connectedAddress = await connectedProvider.getSigner().getAddress();
setAddress(connectedAddress);
setProviderChainID(chainId);
if (chainId === Networks.MAINNET) {
setProvider(connectedProvider);
}
setConnected(true);
return connectedProvider;
}, [provider, web3Modal, connected]);
const checkWrongNetwork = async (): Promise<boolean> => {
if (providerChainID !== DEFAULD_NETWORK) {
const shouldSwitch = window.confirm(messages.switch_to_avalanche);
if (shouldSwitch) {
await swithNetwork();
window.location.reload();
}
return true;
}
return false;
};
const disconnect = useCallback(async () => {
web3Modal.clearCachedProvider();
setConnected(false);
setTimeout(() => {
window.location.reload();
}, 1);
}, [provider, web3Modal, connected]);
const onChainProvider = useMemo(
() => ({
connect,
disconnect,
hasCachedProvider,
provider,
connected,
address,
chainID,
web3Modal,
providerChainID,
checkWrongNetwork,
}),
[connect, disconnect, hasCachedProvider, provider, connected, address, chainID, web3Modal, providerChainID],
);
//@ts-ignore
return <Web3Context.Provider value={{ onChainProvider }}>{children}</Web3Context.Provider>;
}