Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions packages/common/src/types/web3-lib-adapter.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { BigNumberish } from "@ethersproject/bignumber";

export type Log = {
data: string;
topics: string[];
};
export type Log = { data: string; topics: string[] };

export type TransactionRequest = Partial<{
to: string;
Expand Down Expand Up @@ -48,4 +45,5 @@ export interface Web3LibAdapter {
call(transactionRequest: TransactionRequest): Promise<string>;
send(rpcMethod: string, payload: unknown[]): Promise<string>;
getTransactionReceipt(txHash: string): Promise<TransactionReceipt>;
getCurrentTimeMs(): Promise<number>;
}
15 changes: 5 additions & 10 deletions packages/common/tests/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,7 @@ export function mockOfferStruct(overrides?: Partial<OfferStruct>): OfferStruct {
metadataUri: IPFS_URI,
metadataHash: IPFS_HASH,
priceType: PriceType.Static,
royaltyInfo: [
{
recipients: [AddressZero],
bps: [0]
}
],
royaltyInfo: [{ recipients: [AddressZero], bps: [0] }],
...overrides
};
}
Expand Down Expand Up @@ -158,10 +153,10 @@ export class MockWeb3LibAdapter implements Web3LibAdapter {

constructor(returnValues: Partial<MockedWeb3LibReturnValues> = {}) {
this.uuid = crypto.randomUUID();
this._returnValues = {
...defaultMockedReturnValues,
...returnValues
};
this._returnValues = { ...defaultMockedReturnValues, ...returnValues };
}
getCurrentTimeMs(): Promise<number> {
return Promise.resolve(Date.now());
}
async getTransactionReceipt(txHash: string): Promise<TransactionReceipt> {
this.getTransactionReceiptArgs.push(txHash);
Expand Down
26 changes: 18 additions & 8 deletions packages/core-sdk/src/exchanges/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,12 @@ export async function completeExchange(
args.web3Lib.getSignerAddress()
]);

assertCompletableExchange(args.exchangeId, exchange, signerAddress);
await assertCompletableExchange(
args.exchangeId,
exchange,
signerAddress,
args.web3Lib
);

const transactionRequest = {
to: args.contractAddress,
Expand Down Expand Up @@ -257,15 +262,18 @@ export async function completeExchangeBatch(
): Promise<TransactionRequest | TransactionResponse> {
const [exchanges, signerAddress] = await Promise.all([
getExchanges(args.subgraphUrl, {
exchangesFilter: {
id_in: args.exchangeIds.map((id) => id.toString())
}
exchangesFilter: { id_in: args.exchangeIds.map((id) => id.toString()) }
}),
args.web3Lib.getSignerAddress()
]);

for (const exchange of exchanges) {
assertCompletableExchange(exchange.id, exchange, signerAddress);
assertCompletableExchange(
Comment thread
albertfolch-redeemeum marked this conversation as resolved.
Outdated
exchange.id,
exchange,
signerAddress,
args.web3Lib
);
}

const transactionRequest = {
Expand Down Expand Up @@ -522,10 +530,11 @@ function assertSignerIsBuyerOrAssistant(
return { isSignerBuyer, isSignerAssistant };
}

function assertCompletableExchange(
async function assertCompletableExchange(
exchangeId: BigNumberish,
exchange: ExchangeFieldsFragment | null,
signer: string
signer: string,
web3Lib: Web3LibAdapter
) {
assertExchange(exchangeId, exchange);

Expand All @@ -535,8 +544,9 @@ function assertCompletableExchange(
);

if (isSignerAssistant && !isSignerBuyer) {
const now = await web3Lib.getCurrentTimeMs();
const elapsedSinceRedeemMS =
Date.now() - Number(exchange.redeemedDate || "0") * 1000;
now - Number(exchange.redeemedDate || "0") * 1000;
const didDisputePeriodElapse =
elapsedSinceRedeemMS >
Number(exchange.offer.disputePeriodDuration) * 1000;
Expand Down
13 changes: 9 additions & 4 deletions packages/eth-connect-sdk/src/eth-connect-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ export class EthConnectAdapter implements Web3LibAdapter {
this._externalFeatures = externalFeatures;
}

async getCurrentTimeMs(): Promise<number> {
const { timestamp } = await this._requestManager.eth_getBlockByNumber(
"latest",
false
);
return Number(timestamp.valueOf()) * 1000; // Convert seconds to milliseconds
}

public async getSignerAddress() {
if (this._externalFeatures?.getSignerAddress) {
const address = await this._externalFeatures?.getSignerAddress();
Expand Down Expand Up @@ -97,10 +105,7 @@ export class EthConnectAdapter implements Web3LibAdapter {
// Use standard requestManager to fetch blockchain information
const blockNumber = await this._requestManager.eth_blockNumber();
return this._requestManager.eth_call(
{
data: transactionRequest.data,
to: transactionRequest.to
},
{ data: transactionRequest.data, to: transactionRequest.to },
blockNumber
);
}
Expand Down
21 changes: 17 additions & 4 deletions packages/eth-connect-sdk/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const CALL_RET = "call_ret";
const TRANSACTION_COUNT = 64;
const GAS_USED = "87654";
const TX_HASH = "transactionHash";
const nowInSec = Math.floor(Date.now() / 1000);

test("imports EthConnectAdapter", () => {
expect(EthConnectAdapter).toBeTruthy();
Expand Down Expand Up @@ -161,6 +162,17 @@ test("EthConnectAdapter getTransactionReceipt", async () => {
expect(txReceipt.transactionHash).toEqual(TX_HASH);
});

test("EthConnectAdapter getCurrentTimeMs", async () => {
const requestManager = mockRequestManager();
const externalFeatures = mockExternalFeatures();
const ethConnectAdapter = new EthConnectAdapter(
requestManager,
externalFeatures
);
const nowMs = await ethConnectAdapter.getCurrentTimeMs();
expect(nowMs).toBe(nowInSec * 1000); // Convert seconds to milliseconds
});

function mockSigner(wallet: string): RequestManager {
return mockRequestManager(wallet);
}
Expand All @@ -187,7 +199,10 @@ function mockRequestManager(wallet?: string): RequestManager {
},
eth_accounts: async () => (wallet ? [wallet] : WALLETS),
eth_sendTransaction: async (t: any) => TX_HASH,
sendAsync: async (t: any) => TX_HASH
sendAsync: async (t: any) => TX_HASH,
eth_getBlockByNumber: async (blockNumber: string, fullTx: boolean) => {
return { timestamp: nowInSec };
}
} as unknown as RequestManager;
}

Expand All @@ -200,7 +215,5 @@ function mockExternalFeatures(signerAddress?: string): ExternalFeatures {
}
} as ExternalFeatures;
}
return {
delay: async (ms: number) => undefined
} as ExternalFeatures;
return { delay: async (ms: number) => undefined } as ExternalFeatures;
}
5 changes: 5 additions & 0 deletions packages/ethers-sdk/src/ethers-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ export class EthersAdapter implements Web3LibAdapter {
: this._provider.getSigner();
}

async getCurrentTimeMs(): Promise<number> {
const { timestamp } = await this._provider.getBlock("latest");
return timestamp * 1000; // Convert seconds to milliseconds
}

public async getSignerAddress() {
return this._signer.getAddress();
}
Expand Down
21 changes: 14 additions & 7 deletions packages/ethers-sdk/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const BLOCK_NUMBER = "42";
const CALL_RET = "call_ret";
const GAS_USED = "87654";
const TX_HASH = "transactionHash";
const nowInSec = Math.floor(Date.now() / 1000);

test("imports EthersAdapter", () => {
expect(EthersAdapter).toBeTruthy();
Expand All @@ -24,15 +25,15 @@ test("EthersAdapter constructor", () => {
expect(ethersAdapter).toBeTruthy();
});

test("EthConnectAdapter getSignerAddress without signer", async () => {
test("EthersAdapter getSignerAddress without signer", async () => {
const provider = mockProvider();
const ethersAdapter = new EthersAdapter(provider);
expect(ethersAdapter).toBeTruthy();
const signerAddress = await ethersAdapter.getSignerAddress();
expect(signerAddress).toEqual(WALLETS[0]);
});

test("EthConnectAdapter getSignerAddress with signer", async () => {
test("EthersAdapter getSignerAddress with signer", async () => {
const provider = mockProvider();
const signer = mockSigner(WALLETS[2]);
const ethersAdapter = new EthersAdapter(provider, signer);
Expand All @@ -41,6 +42,14 @@ test("EthConnectAdapter getSignerAddress with signer", async () => {
expect(signerAddress).toEqual(WALLETS[2]);
});

test("EthersAdapter getCurrentTimeMs", async () => {
const provider = mockProvider();
const ethersAdapter = new EthersAdapter(provider);
expect(ethersAdapter).toBeTruthy();
const nowMs = await ethersAdapter.getCurrentTimeMs();
expect(nowMs).toBe(nowInSec * 1000); // Convert seconds to milliseconds
});

function mockProvider(): Provider {
return {
getBalance: async () => {
Expand All @@ -58,7 +67,8 @@ function mockProvider(): Provider {
},
send: async () => TX_HASH,
getSigner: () => mockSigner(WALLETS[0]),
getCode: async () => "0x"
getCode: async () => "0x",
getBlock: async () => ({ timestamp: nowInSec })
} as unknown as Provider;
}

Expand All @@ -67,8 +77,5 @@ function mockSigner(wallet: string): Signer {
getAddress: async () => wallet,
getChainId: async () => CHAIN_ID
};
return {
...signer,
connect: () => signer
} as unknown as Signer;
return { ...signer, connect: () => signer } as unknown as Signer;
}
31 changes: 6 additions & 25 deletions packages/react-kit/src/lib/signer/externalSigner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,7 @@ const getDefaultHandleSignerFunction = <R>({
}
}
window.addEventListener("message", onMessageReceived);
window.parent.postMessage(
{
function: functionName,
args
},
parentOrigin
);
window.parent.postMessage({ function: functionName, args }, parentOrigin);
});
};

Expand All @@ -55,6 +49,7 @@ const getExternalWeb3LibAdapterListener = ({
}): Web3LibAdapter => {
return {
uuid: crypto.randomUUID(),
getCurrentTimeMs: () => Promise.resolve(Date.now()),
getSignerAddress: (): Promise<string> => {
return getDefaultHandleSignerFunction<string>({
parentOrigin,
Expand Down Expand Up @@ -145,10 +140,7 @@ const getExternalWeb3LibAdapterListener = ({
}
window.addEventListener("message", onMessageReceived);
window.parent.postMessage(
{
function: functionName,
args: [transactionRequest]
},
{ function: functionName, args: [transactionRequest] },
parentOrigin
);
});
Expand Down Expand Up @@ -289,10 +281,7 @@ const getExternalSignerListener = ({
}
window.addEventListener("message", onMessageReceived);
window.parent.postMessage(
{
function: functionName,
args: [transactionRequest]
},
{ function: functionName, args: [transactionRequest] },
parentOrigin
);
});
Expand Down Expand Up @@ -330,11 +319,7 @@ const getExternalSignerListener = ({
): ReturnType<Signer["populateTransaction"]> => {
return getDefaultHandleSignerFunction<
ReturnType<Signer["populateTransaction"]>
>({
parentOrigin,
functionName: "populateTransaction",
args
});
>({ parentOrigin, functionName: "populateTransaction", args });
},
estimateGas: async (...args: any[]): ReturnType<Signer["estimateGas"]> => {
return getDefaultHandleSignerFunction<ReturnType<Signer["estimateGas"]>>({
Expand All @@ -353,11 +338,7 @@ const getExternalSignerListener = ({
_checkProvider: async (...args: any[]): Promise<void> => {
return getDefaultHandleSignerFunction<
ReturnType<Signer["_checkProvider"]>
>({
parentOrigin,
functionName: "_checkProvider",
args
});
>({ parentOrigin, functionName: "_checkProvider", args });
},
connect: (..._args: any[]): ReturnType<Signer["connect"]> => {
// TODO: how can we implement this?
Expand Down
Loading