ethers#Event TypeScript Examples
The following examples show how to use
ethers#Event.
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: EventProcessor.ts From l2beat with MIT License | 6 votes |
//TODO: Add cache !
async processEvent(event: Event) {
let implOfProxyName = ''
const [timestamp, implementationName] = await Promise.all([
this.blockTimestampService.getBlockTimestamp(event.blockNumber),
this.addressAnalyzer.getName(event.args?.agent),
])
if (implementationName === 'OwnedUpgradabilityProxy') {
const implContract = new Contract(
event.args?.agent,
['function implementation() view returns (address)'],
this.provider
)
const implementationAddress = await implContract.implementation()
implOfProxyName = await this.addressAnalyzer.getName(
implementationAddress
)
}
return {
blockNumber: event.blockNumber,
transactionHash: event.transactionHash,
user: event.args?.user as string,
agent: event.args?.agent as string,
timestamp,
implementationName,
implOfProxyName,
}
}
Example #2
Source File: singlePubkeyRegistered.ts From hubble-contracts with MIT License | 6 votes |
private async handleSinglePubkeyRegistered(event: Event) {
const pubkeyID = event.args?.pubkeyID;
const txn = await event.getTransaction();
const pubkey = this.getPubkeyFromTxn(txn);
await this.pubkeyStorage.update(pubkeyID, pubkey);
console.info(`Pubkey added ID ${pubkeyID} ${pubkey.toString()}`);
}
Example #3
Source File: newBatch.ts From hubble-contracts with MIT License | 6 votes |
private async handleNewBatch(event: Event) {
const batchID = Number(event.args?.batchID);
if (this.syncpoint.batchID >= batchID) {
console.info(
"synced before",
"synced batchID",
this.syncpoint.batchID,
"this batchID",
batchID
);
return;
}
const usage = event.args?.batchType as Usage;
this.batchHandlingContext.setStrategy(usage);
const batch = await this.batchHandlingContext.parseBatch(event);
await this.batchStorage.add(batch, { hash: event.transactionHash });
const txns = await this.batchHandlingContext.processBatch(batch);
for (const tx of txns) {
// TODO Figure out finalization
// https://github.com/thehubbleproject/hubble-contracts/issues/592
const finalized = false;
const l1BlockIncluded = -1;
await this.transactionStorage.sync(tx, {
finalized,
batchID,
l1TxnHash: event.transactionHash,
l1BlockIncluded
});
}
this.syncpoint.update(event.blockNumber, batchID);
console.info(`#${batchID} [${Usage[usage]}]`, batch.toString());
}
Example #4
Source File: depositsFinalised.ts From hubble-contracts with MIT License | 6 votes |
private handleDepositsFinalised(event: Event) {
if (!event.args) {
throw new Error("missing event args");
}
const { subtreeID, pathToSubTree } = event.args;
const subIDStr = subtreeID.toString();
console.log(`subtree #${subIDStr} submitted`);
const pendingDeposits = this.subtreeIDToPendingDeposits[subIDStr];
if (!pendingDeposits) {
throw new Error(
`pending deposits not found for subtreeID ${subIDStr}`
);
}
delete this.subtreeIDToPendingDeposits[subIDStr];
for (const pd of pendingDeposits) {
const stateID = pathToSubTree
.mul(2 ** this.maxDepositSubtreeDepth)
.add(pd.depositID);
const tokenIDStr = pd.tokenID.toString();
this.feeReceivers.push({
tokenID: tokenIDStr,
stateID: stateID.toString()
});
console.log(
`deposit for tokenID ${tokenIDStr} packed.`,
`stateID ${stateID.toString()}`
);
}
}
Example #5
Source File: depositQueued.ts From hubble-contracts with MIT License | 6 votes |
depositQueuedListener = (
pubkeyID: null,
tokenID: null,
l2Amount: null,
subtreeID: null,
depositID: null,
event: Event
) => {
this.handleDepositQueued(event);
};
Example #6
Source File: batchPubkeyRegistered.ts From hubble-contracts with MIT License | 6 votes |
batchPubkeyRegisteredListener = async (
startID: null,
endID: null,
event: Event
) => {
await this.handleBatchPubkeyRegistered(event);
// unused with db engine
await this.commitUpdate();
};
Example #7
Source File: batchPubkeyRegistered.ts From hubble-contracts with MIT License | 6 votes |
private async handleBatchPubkeyRegistered(event: Event) {
let startID = event.args?.startID;
const txn = await event.getTransaction();
const keysBatch = this.getPubkeysFromTxn(txn);
const baseIndex = 2 ** (PRODUCTION_PARAMS.MAX_DEPTH - 1);
let nextIndex = baseIndex + Number(startID);
for (const key of keysBatch) {
await this.pubkeyStorage.update(nextIndex, key);
console.info(`Pubkey added ID ${nextIndex} ${key.toString()}`);
nextIndex++;
}
}
Example #8
Source File: transfer.ts From hubble-contracts with MIT License | 6 votes |
async parseBatch(event: Event): Promise<Batch> {
const ethTx = await event.getTransaction();
const data = ethTx?.data as string;
const accountRoot = event.args?.accountRoot;
const txDescription = this.rollup.interface.parseTransaction({ data });
const {
stateRoots,
signatures,
feeReceivers,
txss
} = txDescription.args;
const commitments = [];
for (let i = 0; i < stateRoots.length; i++) {
const commitment = new TransferCommitment(
stateRoots[i],
accountRoot,
signatures[i],
feeReceivers[i],
txss[i]
);
commitments.push(commitment);
}
return new ConcreteBatch(commitments);
}
Example #9
Source File: genesis.ts From hubble-contracts with MIT License | 6 votes |
public async parseBatch(event: Event): Promise<Batch> {
const batchIDBN = event.args?.batchID as BigNumber;
const batchID = batchIDBN.toNumber();
this.validateIsFirstBatch(batchID);
// Reconstruct genesis batch from genesis state root
const commitment = new GenesisCommitment(this.genesisStateRoot);
const batch = new ConcreteBatch([commitment]);
// Get genesis batch from L1
const l1Batch = await this.rollup.getBatch(batchIDBN);
// Verify match
if (l1Batch.commitmentRoot !== batch.commitmentRoot) {
throw new GenesisBatchCommitmentRootMismatch(
l1Batch.commitmentRoot,
batch.commitmentRoot
);
}
return batch;
}
Example #10
Source File: deposit.ts From hubble-contracts with MIT License | 6 votes |
export async function handleNewBatch(
event: Event,
rollup: Rollup
): Promise<ConcreteBatch<DepositCommitment>> {
const ethTx = await event.getTransaction();
const data = ethTx?.data as string;
const receipt = await event.getTransactionReceipt();
const logs = receipt.logs.map(log => rollup.interface.parseLog(log));
const depositsFinalisedLog = logs.filter(
log => log.signature === "DepositsFinalised(uint256,bytes32,uint256)"
)[0];
const txDescription = rollup.interface.parseTransaction({ data });
const depositSubtreeRoot = depositsFinalisedLog.args?.depositSubTreeRoot;
const subtreeID = depositsFinalisedLog.args?.subtreeID;
const { vacant } = txDescription.args;
const pathAtDepthNum = vacant.pathAtDepth.toNumber();
const stateRoot = computeRoot(
depositSubtreeRoot,
pathAtDepthNum,
vacant.witness
);
const context: FinalizationContext = {
subtreeID,
depositSubtreeRoot,
pathToSubTree: pathAtDepthNum
};
const commitment = new DepositCommitment(stateRoot, context);
return new ConcreteBatch([commitment]);
}
Example #11
Source File: batchHandler.ts From hubble-contracts with MIT License | 6 votes |
export async function handleNewBatch(
event: Event,
rollup: Rollup
): Promise<Batch> {
const ethTx = await event.getTransaction();
const data = ethTx?.data as string;
const txDescription = rollup.interface.parseTransaction({ data });
const batchID = event.args?.batchID;
const batchType = event.args?.batchType;
const accountRoot = event.args?.accountRoot;
const batch = batchFactory(batchType, txDescription, accountRoot);
const commitmentRoot = (await rollup.batches(batchID)).commitmentRoot;
if (batch.commitmentRoot != commitmentRoot) {
throw new Error(
`Mismatched commitmentRoot onchain ${commitmentRoot} parsed ${batch.commitmentRoot}`
);
}
return batch;
}
Example #12
Source File: EventProcessor.ts From l2beat with MIT License | 6 votes |
async processEvent(event: Event) {
const [timestamp, name, implementationName] = await Promise.all([
this.blockTimestampService.getBlockTimestamp(event.blockNumber),
this.optimismNameService.getOptimismName(
event.args?.name.hash,
event.transactionHash
),
this.addressAnalyzer.getName(event.args?.newAddress),
])
return {
blockNumber: event.blockNumber,
transactionHash: event.transactionHash,
nameHash: event.args?.name.hash as string,
oldAddress: event.args?.oldAddress as string,
newAddress: event.args?.newAddress as string,
timestamp,
name,
implementationName,
}
}
Example #13
Source File: deposit.ts From hubble-contracts with MIT License | 5 votes |
public async parseBatch(event: Event) {
return await handleNewBatch(event, this.rollup);
}
Example #14
Source File: contractEventSyncer.ts From hubble-contracts with MIT License | 5 votes |
protected async getEvents(
startBlock: number,
endBlock: number
): Promise<Event[]> {
return this.contract.queryFilter(this.filter, startBlock, endBlock);
}
Example #15
Source File: depositQueued.ts From hubble-contracts with MIT License | 5 votes |
private handleDepositQueued(event: Event) {
const depositState = State.fromDepositQueuedEvent(event);
this.depositPool.pushDeposit(depositState.encode());
console.info(`Deposit queued ${depositState.toString()}`);
}
Example #16
Source File: depositsFinalised.ts From hubble-contracts with MIT License | 5 votes |
depositsFinalisedListener = (
subtreeID: null,
depositSubTreeRoot: null,
pathToSubTree: null,
event: Event
) => {
this.handleDepositsFinalised(event);
};
Example #17
Source File: newBatch.ts From hubble-contracts with MIT License | 5 votes |
newBatchListener = async (
batchID: null,
accountRoot: null,
batchType: null,
event: Event
) => {
await this.handleNewBatch(event);
};
Example #18
Source File: singlePubkeyRegistered.ts From hubble-contracts with MIT License | 5 votes |
singlePubkeyRegisteredListener = async (pubkeyID: null, event: Event) => {
await this.handleSinglePubkeyRegistered(event);
await this.commitUpdate();
};
Example #19
Source File: state.ts From hubble-contracts with MIT License | 5 votes |
static fromDepositQueuedEvent(event: Event): State {
if (!event.args) {
throw new Error("DepositQueued event missing args");
}
const { pubkeyID, tokenID, l2Amount } = event.args;
return State.new(pubkeyID, tokenID, l2Amount, 0);
}
Example #20
Source File: state.tsx From nft-market with MIT License | 4 votes |
useAppState = create<StateContext>((set, get) => ({
isAuthenticated: false,
contract: undefined,
user: undefined,
tokensOnSale: [],
ethPrice: '0.0',
activatingConnector: undefined,
transaction: undefined,
setAuthenticated: (authenticated: boolean) => set({ isAuthenticated: authenticated }),
setContract: async (library: any, chainId: number) => {
try {
if (!library) throw new Error('No Web3 Found')
const networkid = (id: number) => {
switch (id) {
case 1337:
return 5777
default:
return id
}
}
const deployedNetwork =
NFTT.networks[String(networkid(chainId)) as keyof typeof NFTT.networks]
if (!deployedNetwork) {
throw new Error('The network you selected is no supported yet.')
}
const { address } = deployedNetwork
const contract = new Contract(address, NFTT.abi, library.getSigner())
const name = await contract.name()
const symbol = await contract.symbol()
set({
library,
contract,
contractDetails: {
name,
symbol,
address,
},
})
} catch (e) {
console.log(e)
}
},
setUser: async (address?: string) => {
try {
const { contract, user, library, getUserTokens } = get()
if (!library) throw new Error('No Web3 Found')
if (!contract) throw new Error('No contract found')
if (!user && !address) throw new Error('No user found')
const balance = utils.formatEther(await library.getBalance(address || user?.address || ''))
const ownedTokens = await getUserTokens(address || user?.address)
set({
isAuthenticated: true,
user: { address: address || user?.address || '', balance, ownedTokens },
})
} catch (e) {
console.log(e)
}
},
setTokensOnSale: (tokensOnSale: TokenProps[]) => set({ tokensOnSale: tokensOnSale }),
setEthPrice: (ethPrice: string) => set({ ethPrice: ethPrice }),
setActivatingConnector: (activatingConnector: any) =>
set({ activatingConnector: activatingConnector }),
setTransaction: (transaction: any) => set({ transaction: transaction }),
//
getUserTokens: async (address?: string): Promise<TokenProps[]> => {
try {
const { contract, library, user } = get()
if (!library) throw new Error('No Web3 Found')
if (!contract) throw new Error('No contract found')
if (!user?.address && !address) throw new Error('No user found')
const userAddress = user?.address || address
const ownedTokensEvents = contract.filters.Transfer(null, userAddress)
const results: Event[] = await contract.queryFilter(ownedTokensEvents, 0, 'latest')
const ownedTokens: Map<string, TokenProps> = new Map()
await Promise.all(
results.map(async current => {
const ownerToken = await contract.ownerOf(current.args?.tokenId)
if (ownerToken === userAddress) {
const { id, name, price } = await contract.tokenMeta(current.args?.tokenId)
const uri = await contract.tokenURI(current.args?.tokenId)
ownedTokens.set(uri, {
id,
name,
price,
uri,
})
}
})
)
return Array.from(ownedTokens).map(([_, token]) => token)
} catch (e) {
console.log(e)
return []
}
},
buyToken: async (id: string, price: BigNumber) => {
try {
const { setTransaction, contract } = get()
if (!contract) throw new Error('No contract found')
const tx = await contract.purchaseToken(id, { value: price })
setTransaction(tx)
} catch (e) {
console.log('on buy', e)
}
},
//
updateTokensOnSale: async () => {
try {
const { contract, setTokensOnSale } = get()
if (!contract) throw new Error('No contract found')
const tokensForSale = (await contract.getAllOnSale()).reduce((acc: TokenProps[], b: any) => {
if (b.uri !== '') {
acc.push({ id: b.id, price: b.price, name: b.name, uri: b.uri })
}
return acc
}, [] as TokenProps[])
setTokensOnSale(tokensForSale)
return true
} catch (e) {
console.log(e)
return false
}
},
//
setTokenSale: async (id: string, price: BigNumber, onSale: boolean = false) => {
try {
const { contract, user, setTransaction } = get()
if (!contract) throw new Error('No contract found')
if (!user) throw new Error('No user found')
const tx = await contract.setTokenSale(id, onSale, price, { from: user.address })
setTransaction(tx)
return true
} catch (e) {
console.log(e)
return false
}
},
//
transferToken: async (id: string, to: string) => {
try {
const { contract, user, setTransaction } = get()
if (!contract) throw new Error('No contract found')
if (!user) throw new Error('No user found')
const tx = await contract['safeTransferFrom(address,address,uint256)'](user.address, to, id, {
from: user.address,
})
// console.log(tx)
setTransaction(tx)
} catch (e) {
console.log(e)
}
},
}))
Example #21
Source File: ContractsAPI.ts From client with GNU General Public License v3.0 | 4 votes |
public async setupEventListeners(): Promise<void> {
const { contract } = this;
const filter = {
address: contract.address,
topics: [
[
contract.filters.ArrivalQueued(null, null, null, null, null).topics,
contract.filters.ArtifactActivated(null, null, null).topics,
contract.filters.ArtifactDeactivated(null, null, null).topics,
contract.filters.ArtifactDeposited(null, null, null).topics,
contract.filters.ArtifactFound(null, null, null).topics,
contract.filters.ArtifactWithdrawn(null, null, null).topics,
contract.filters.LocationRevealed(null, null, null, null).topics,
contract.filters.PlanetHatBought(null, null, null).topics,
contract.filters.PlanetProspected(null, null).topics,
contract.filters.PlanetSilverWithdrawn(null, null, null).topics,
contract.filters.PlanetTransferred(null, null, null).topics,
contract.filters.PlanetInvaded(null, null).topics,
contract.filters.PlanetCaptured(null, null).topics,
contract.filters.PlayerInitialized(null, null).topics,
contract.filters.AdminOwnershipChanged(null, null).topics,
contract.filters.AdminGiveSpaceship(null, null).topics,
contract.filters.PauseStateChanged(null).topics,
contract.filters.LobbyCreated(null, null).topics,
].map((topicsOrUndefined) => (topicsOrUndefined || [])[0]),
] as Array<string | Array<string>>,
};
const eventHandlers = {
[ContractEvent.PauseStateChanged]: (paused: boolean) => {
this.emit(ContractsAPIEvent.PauseStateChanged, paused);
},
[ContractEvent.AdminOwnershipChanged]: (location: EthersBN, _newOwner: string) => {
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(location));
},
[ContractEvent.AdminGiveSpaceship]: (
location: EthersBN,
_newOwner: string,
_type: ArtifactType
) => {
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(location));
},
[ContractEvent.ArtifactFound]: (
_playerAddr: string,
rawArtifactId: EthersBN,
loc: EthersBN
) => {
const artifactId = artifactIdFromEthersBN(rawArtifactId);
this.emit(ContractsAPIEvent.ArtifactUpdate, artifactId);
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(loc));
},
[ContractEvent.ArtifactDeposited]: (
_playerAddr: string,
rawArtifactId: EthersBN,
loc: EthersBN
) => {
const artifactId = artifactIdFromEthersBN(rawArtifactId);
this.emit(ContractsAPIEvent.ArtifactUpdate, artifactId);
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(loc));
},
[ContractEvent.ArtifactWithdrawn]: (
_playerAddr: string,
rawArtifactId: EthersBN,
loc: EthersBN
) => {
const artifactId = artifactIdFromEthersBN(rawArtifactId);
this.emit(ContractsAPIEvent.ArtifactUpdate, artifactId);
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(loc));
},
[ContractEvent.ArtifactActivated]: (
_playerAddr: string,
rawArtifactId: EthersBN,
loc: EthersBN
) => {
const artifactId = artifactIdFromEthersBN(rawArtifactId);
this.emit(ContractsAPIEvent.ArtifactUpdate, artifactId);
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(loc));
},
[ContractEvent.ArtifactDeactivated]: (
_playerAddr: string,
rawArtifactId: EthersBN,
loc: EthersBN
) => {
const artifactId = artifactIdFromEthersBN(rawArtifactId);
this.emit(ContractsAPIEvent.ArtifactUpdate, artifactId);
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(loc));
},
[ContractEvent.PlayerInitialized]: async (player: string, locRaw: EthersBN, _: Event) => {
this.emit(ContractsAPIEvent.PlayerUpdate, address(player));
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(locRaw));
this.emit(ContractsAPIEvent.RadiusUpdated);
},
[ContractEvent.PlanetTransferred]: async (
_senderAddress: string,
planetId: EthersBN,
receiverAddress: string,
_: Event
) => {
this.emit(
ContractsAPIEvent.PlanetTransferred,
locationIdFromEthersBN(planetId),
address(receiverAddress)
);
},
[ContractEvent.ArrivalQueued]: async (
playerAddr: string,
arrivalId: EthersBN,
fromLocRaw: EthersBN,
toLocRaw: EthersBN,
_artifactIdRaw: EthersBN,
_: Event
) => {
this.emit(
ContractsAPIEvent.ArrivalQueued,
arrivalId.toString() as VoyageId,
locationIdFromEthersBN(fromLocRaw),
locationIdFromEthersBN(toLocRaw)
);
this.emit(ContractsAPIEvent.PlayerUpdate, address(playerAddr));
this.emit(ContractsAPIEvent.RadiusUpdated);
},
[ContractEvent.PlanetUpgraded]: async (
_playerAddr: string,
location: EthersBN,
_branch: EthersBN,
_toBranchLevel: EthersBN,
_: Event
) => {
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(location));
},
[ContractEvent.PlanetInvaded]: async (_playerAddr: string, location: EthersBN, _: Event) => {
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(location));
},
[ContractEvent.PlanetCaptured]: async (_playerAddr: string, location: EthersBN, _: Event) => {
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(location));
},
[ContractEvent.PlanetHatBought]: async (
_playerAddress: string,
location: EthersBN,
_: Event
) => this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(location)),
[ContractEvent.LocationRevealed]: async (
revealerAddr: string,
location: EthersBN,
_x: EthersBN,
_y: EthersBN,
_: Event
) => {
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(location));
this.emit(
ContractsAPIEvent.LocationRevealed,
locationIdFromEthersBN(location),
address(revealerAddr.toLowerCase())
);
this.emit(ContractsAPIEvent.PlayerUpdate, address(revealerAddr));
},
[ContractEvent.PlanetSilverWithdrawn]: async (
player: string,
location: EthersBN,
_amount: EthersBN,
_: Event
) => {
this.emit(ContractsAPIEvent.PlanetUpdate, locationIdFromEthersBN(location));
this.emit(ContractsAPIEvent.PlayerUpdate, address(player));
},
[ContractEvent.LobbyCreated]: (ownerAddr: string, lobbyAddr: string) => {
this.emit(ContractsAPIEvent.LobbyCreated, address(ownerAddr), address(lobbyAddr));
},
};
this.ethConnection.subscribeToContractEvents(contract, eventHandlers, filter);
}