Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PR: claim permit in gift cards #226

Merged
merged 101 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from 56 commits
Commits
Show all changes
101 commits
Select commit Hold shift + click to select a range
90ee27f
feat: claim permit in gift cards
EresDev Apr 23, 2024
5426f77
refactor: move addresses to constants from env
EresDev May 13, 2024
e0a787b
fix: compares owner address case insensitive
EresDev May 13, 2024
7a61714
fix: deduct fee from reward amount
EresDev May 13, 2024
abf145f
fix: show unavailable range cards price correctly
EresDev May 13, 2024
2aada64
refactor: rename func to clear its effect
EresDev May 13, 2024
52c0979
fix: use correct pricing for gift card
EresDev May 16, 2024
f1d58c3
refactor: move pricing & duplicatre code to proper files/vars
EresDev May 16, 2024
9ebe8f0
fix: offer only visa & mastercard
EresDev May 16, 2024
47e644e
fix: add disclaimer below gift cards list
EresDev May 16, 2024
56cba03
docs: add info about API base url
EresDev May 16, 2024
cf21902
fix: allow only ERC20 permit to claim card
EresDev May 16, 2024
f056b9d
fix: prevent large prices to take second line on cards list
EresDev May 16, 2024
ed6c28e
chore: run missing yarn install from previous merge
EresDev May 16, 2024
afe5f9e
chore: handle cspell warnings by listing & fixing words
EresDev May 16, 2024
84763f3
refactor: replace word usage product with gift-card
EresDev May 16, 2024
8d18bba
fix: check permit transfers correct erc20 token on claim gift card
EresDev May 17, 2024
7cc3fc5
fix: check permit token owner is correct on claim gift card
EresDev May 17, 2024
8fe9b2b
fix: validate correct token transfer on different chains
EresDev May 17, 2024
83b816a
refactor: allow tests to generate permits without CLI
EresDev May 21, 2024
bd17ddb
fix: show price/value upto 2 decimals in title
EresDev May 21, 2024
eff0545
test: add tests for claiming gift cards
EresDev May 21, 2024
d12b9bb
fix: add date filter to retrieve old order
EresDev May 22, 2024
0e909ec
test: ignore balance because it changes with tests
EresDev May 22, 2024
082f52b
chore: fix spell
EresDev May 22, 2024
678ca44
fix: run wrangler in workflow for backend in tests
EresDev May 23, 2024
e28ac13
fix: use reloadly sandbox by default
EresDev May 23, 2024
5dee0f7
fix: log if using reloadly sandbox or not
EresDev May 23, 2024
c16253d
fix: change anvil RPC to fork for tests
EresDev May 23, 2024
530f3d1
fix: start wrangler in action for tests backend
EresDev May 23, 2024
fa20756
fix: only show visa & mastercard
EresDev May 23, 2024
878d7cb
test: buy minimum available visa or mastercard
EresDev May 23, 2024
ae9b341
test: reveal code of already claimed visa
EresDev May 23, 2024
d4f8be2
fix: remove fixed chainId from test for gift card claim
EresDev May 23, 2024
926e9f1
fix: wait 2 sec for page to laod in test
EresDev May 23, 2024
3212a26
fix: remove invalid expectation from test
EresDev May 23, 2024
9f770ae
test: extract interceptors to remove duplication
EresDev May 24, 2024
cf608e5
refactor: rename var
EresDev May 24, 2024
e695cac
test: make claim gift card test more reliable
EresDev May 24, 2024
238aae3
fix: return 404 if order not found insteaf of 500
EresDev May 24, 2024
0ed7b52
refactor: change types to interfaces
EresDev May 25, 2024
4de57e0
refactor: rename interface
EresDev May 25, 2024
20c830d
refactor: replace types with interfaces
EresDev May 25, 2024
2e3d5e9
fix: align gift cards to center when less than 3
EresDev May 25, 2024
1963c65
fix: remove unnecessary text
EresDev May 25, 2024
1bd43f1
fix: inform properly when gift card unavailable
EresDev May 25, 2024
d5503a0
refactor: load visa & mastercard concurrently
EresDev May 25, 2024
2cfabc9
fix: reload gift cards when next/prev permit loads
EresDev May 25, 2024
b09fb16
fix: use websocket rpc for faster & reliable tests
EresDev May 25, 2024
1bb6211
fix: improve light mode support for gift cards
EresDev May 25, 2024
344befd
fix: separate matching & available price
EresDev May 25, 2024
8736d1a
refactor: rename function
EresDev May 25, 2024
376c9f2
fix: show gift card loader on page load
EresDev May 25, 2024
56d7a95
fix: await before printing in erc20 permit gen
EresDev May 25, 2024
f9b16c0
chore: use wrangler to server UI & backend
EresDev May 25, 2024
8fa0b09
chore: add gnosischain to accepted words in cspell
EresDev May 25, 2024
c0e71f7
chore: remove tenderly rpc
EresDev May 27, 2024
3c056ca
chore: show mastercard before visa cards
EresDev May 27, 2024
de33f42
fix: prevent exception on zero value
EresDev May 27, 2024
acec598
fix: reuse existing permit health check
EresDev May 27, 2024
1d89eea
fix: make the height of card img fixed to align
EresDev May 27, 2024
8cce139
fix: check of negative status to fail an order
EresDev May 27, 2024
ec7292a
fix: make redeem code visible as case sensitive & wrapped
EresDev May 27, 2024
4fb3568
fix: improve order processing messages
EresDev May 27, 2024
76916a3
test: update gift card order msgs assertions
EresDev May 27, 2024
77c1cbf
Merge branch 'development' of https://github.com/ubiquity/pay.ubq.fi …
EresDev May 27, 2024
1135a4f
chore: run missed yarn install from previous merge
EresDev May 31, 2024
214f730
refactor: change arrow functions to named functions
EresDev May 31, 2024
ae48f8a
refactor: reduce function complexity
EresDev May 31, 2024
7732866
refactor: replace string concatination with array push
EresDev May 31, 2024
70381cc
refactor: move disclaimer to static html
EresDev May 31, 2024
2a2325a
refactor: utilize run-s to run seq start scripts
EresDev May 31, 2024
5ae08db
refactor: shorten the variable name
EresDev May 31, 2024
4ec8c66
fix: use fastest rpc from @ubiquity-dao/rpc-handler
EresDev Jun 3, 2024
c4b1d6b
fix: fork anvil network from fastest rpc
EresDev Jun 3, 2024
76daaba
fix: prevent nonce collision on fund
EresDev Jun 3, 2024
222bd0c
refactor: remove unnecessary & error-prone code
EresDev Jun 3, 2024
68dfa23
fix: use new cloudflare deploy action
EresDev Jun 8, 2024
4d32dac
fix: readme
Keyrxng Jun 10, 2024
135951a
chore: readme what to expect
Keyrxng Jun 10, 2024
1d197c6
chore: readme remove cloudflare steps
Keyrxng Jun 10, 2024
049eae5
fix: barely english
Keyrxng Jun 10, 2024
9992a62
chore: readme title, desc and rearrange
Keyrxng Jun 10, 2024
77e6fb4
fix: readme typo
Keyrxng Jun 10, 2024
614e678
fix: move controls into sight
Keyrxng Jun 10, 2024
3c45c07
fix: use pixels and remove large on ERC20
Keyrxng Jun 11, 2024
33d2148
chore: more concise readme
Keyrxng Jun 12, 2024
692064b
chore: readme additional error
Keyrxng Jun 12, 2024
d1caf1a
fix: link after claim
Keyrxng Jun 13, 2024
f36fdb8
fix: view claim test
Keyrxng Jun 13, 2024
f703fb6
chore: use blockscan explorer
Keyrxng Jun 15, 2024
4a2b8d1
chore: move add. details up
Keyrxng Jun 16, 2024
b7dd348
Merge pull request #248 from ubq-testing/nft-table-fix
0x4007 Jun 17, 2024
114e59a
Merge pull request #246 from ubq-testing/refactor/readme
0x4007 Jun 17, 2024
aa003e2
Merge pull request #251 from ubq-testing/fix/view-claim
0x4007 Jun 17, 2024
a29fe52
Merge branch 'development' of https://github.com/ubiquity/pay.ubq.fi …
EresDev Jun 17, 2024
d41e510
fix: show purchased gift card without page reload
EresDev Jun 17, 2024
54d5bb9
fix: add 'blockscan' to cspell words list
EresDev Jun 17, 2024
c7d44c9
fix: use correct env vars
EresDev Jun 17, 2024
0495045
fix: update test expected message
EresDev Jun 17, 2024
c275979
fix: remove permit signer check
EresDev Jun 17, 2024
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
4 changes: 4 additions & 0 deletions .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"devpool",
"ethersproject",
"fract",
"giftcards",
"gnosischain",
"gnosisscan",
"godb",
"greyscale",
Expand All @@ -23,6 +25,8 @@
"libsodium",
"Numberish",
"outdir",
"pageable",
"Reloadly",
"Rpcs",
"scalarmult",
"servedir",
Expand Down
5 changes: 4 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,7 @@ jobs:
uses: actions/upload-artifact@v4
with:
name: static
path: static
path: |
static
functions
shared
9 changes: 8 additions & 1 deletion .github/workflows/cypress-testing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,17 @@ jobs:
- name: Start Anvil
run: yarn test:anvil &

- name: Start Cloudflare Wrangler
run: npx wrangler pages dev static --port 8080 --binding USE_RELOADLY_SANDBOX=true RELOADLY_API_CLIENT_ID="$RELOADLY_SANDBOX_API_CLIENT_ID" RELOADLY_API_CLIENT_SECRET="$RELOADLY_SANDBOX_API_CLIENT_SECRET" &
env:
RELOADLY_SANDBOX_API_CLIENT_ID: ${{ secrets.RELOADLY_SANDBOX_API_CLIENT_ID }}
RELOADLY_SANDBOX_API_CLIENT_SECRET: ${{ secrets.RELOADLY_SANDBOX_API_CLIENT_SECRET }}

- name: Cypress run
uses: cypress-io/github-action@v6
with:
build: yarn run build
start: yarn test:fund, yarn start
start: yarn test:fund

env:
SUPABASE_URL: "https://wfzpewmlyiozupulbuur.supabase.co"
Expand All @@ -52,6 +58,7 @@ jobs:
PAYMENT_TOKEN_ADDRESS: "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d"
RPC_PROVIDER_URL: "http://localhost:8545"
UBIQUIBOT_PRIVATE_KEY: "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d"

- uses: actions/upload-artifact@v4
if: failure()
with:
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ commit.txt
static/dist

cypress/screenshots
cypress/videos
cypress/videos
.wrangler
3 changes: 3 additions & 0 deletions cypress.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ export default defineConfig({
setupNodeEvents() {},
baseUrl: "http://localhost:8080",
experimentalStudio: true,
env: {
permitConfig: { ...process.env },
},
},
viewportHeight: 900,
viewportWidth: 1440,
Expand Down
196 changes: 196 additions & 0 deletions cypress/e2e/claim-gift-card.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/* eslint-disable sonarjs/no-duplicate-string */
import { JsonRpcProvider, JsonRpcSigner } from "@ethersproject/providers";
import { Wallet } from "ethers";
import { PermitConfig, generateERC20Permit } from "../../scripts/typescript/generate-erc20-permit-url";

const beneficiary = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"; // anvil
const SENDER_PRIVATE_KEY = "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d"; // anvil

describe("Gift Cards", () => {
beforeEach(() => {
cy.clearAllCookies();
cy.clearAllLocalStorage();
cy.clearAllSessionStorage();
setupStubs();

setupIntercepts();
});

it("should show/hide activation info", () => {
const permitConfig = Cypress.env("permitConfig");
void cy.getPermitUrl(permitConfig).then((permitUrl) => {
cy.visit(`${permitUrl as string}`);
cy.wait(2000);

cy.wait("@listGiftCards");

cy.get("#gift-cards").should("exist").and("include.text", "Or claim in virtual visa/mastercard");
cy.get(".gift-card").should("have.length.above", 0);

cy.get(".gift-card.purchased").should("not.exist");

cy.get('#activate-info .redeem-info-wrapper[data-show="true"]').should("not.exist");
cy.get(".gift-card").eq(0).find(".activate-btn").invoke("click");

cy.get('#activate-info .redeem-info-wrapper[data-show="true"]').should("exist");
cy.get("#activate-info .close-btn").invoke("click");
cy.get('#activate-info .redeem-info-wrapper[data-show="true"]').should("not.exist");
});
});

it("should claim a gift card", () => {
const permitConfig = Cypress.env("permitConfig");

const customPermitConfig = { ...permitConfig, AMOUNT_IN_ETH: "30.0" };

void cy.getPermitUrl(customPermitConfig).then((permitUrl) => {
cy.visit(permitUrl);
cy.wait(2000);

cy.wait("@listGiftCards");
cy.get(".gift-card").should("have.length.above", 0);
cy.get(".gift-card .available").should("have.length.above", 0);
cy.get(".gift-card .available")
.eq(0)
.parent()
.parent()
.find("h3")
.eq(0)
.then(($name) => {
const giftCardName = $name;
cy.wrap(giftCardName).as("giftCardName");
});

cy.intercept({ method: "POST", url: "/post-order" }).as("postOrder");

cy.get(".gift-card .available").eq(0).parent().parent().find(".claim-gift-card-btn").should("have.length", 1);

cy.intercept({ method: "GET", url: "/get-order**" }).as("getOrder");
cy.get(".gift-card .available").eq(0).parent().parent().find(".claim-gift-card-btn").invoke("click");
cy.get(".notifications", { timeout: 10000 }).should("contain.text", "Transaction sent");
cy.get(".notifications", { timeout: 10000 }).should("contain.text", "Payment confirmed. Claiming card now...");
cy.wait("@getOrder", { timeout: 10000 });

cy.get("#gift-cards").should("exist").and("include.text", "Your gift card");

cy.get("@giftCardName").then((name) => {
cy.get(".gift-card h3")
.eq(0)
.should("have.text", name.text() as string);
});
});
});

it("should reveal a redeem code after claim", () => {
cy.visit(
"http://localhost:8080/?claim=W3sidHlwZSI6ImVyYzIwLXBlcm1pdCIsInBlcm1pdCI6eyJwZXJtaXR0ZWQiOnsidG9rZW4iOiIweGU5MUQxNTNFMGI0MTUxOEEyQ2U4RGQzRDc5NDRGYTg2MzQ2M2E5N2QiLCJhbW91bnQiOiIzMDAwMDAwMDAwMDAwMDAwMDAwMCJ9LCJub25jZSI6IjczMDU2NzU0MjU1ODU4ODMxMzQ0NTMzNDgxMDc0Njg5NTE1ODEyNzIzNDE5NTkwNjMwOTY2MTUwOTIxNzk3ODEzMzExMDE4NjgyMDMzIiwiZGVhZGxpbmUiOiIxMTU3OTIwODkyMzczMTYxOTU0MjM1NzA5ODUwMDg2ODc5MDc4NTMyNjk5ODQ2NjU2NDA1NjQwMzk0NTc1ODQwMDc5MTMxMjk2Mzk5MzUifSwidHJhbnNmZXJEZXRhaWxzIjp7InRvIjoiMHhmMzlGZDZlNTFhYWQ4OEY2RjRjZTZhQjg4MjcyNzljZmZGYjkyMjY2IiwicmVxdWVzdGVkQW1vdW50IjoiMzAwMDAwMDAwMDAwMDAwMDAwMDAifSwib3duZXIiOiIweDcwOTk3OTcwQzUxODEyZGMzQTAxMEM3ZDAxYjUwZTBkMTdkYzc5QzgiLCJzaWduYXR1cmUiOiIweDdkYWYxMTNhNTA0ZjYxYzk5MDg0ZGM2ZGFlZTZkZDFkZjhhM2I4YjM5ZTU0N2VkYWIxMjNhNzQxNjBhNWVhNDYwZDgyODdmYWM1MDlhYTc5M2ZhNjc5M2RlOTg5YmVhOTg4Y2M3NDAyNGE5ZmQyNjAyMjY2YTQzZjg1MDlhYTJkMWIiLCJuZXR3b3JrSWQiOjMxMzM3fSx7InR5cGUiOiJlcmMyMC1wZXJtaXQiLCJwZXJtaXQiOnsicGVybWl0dGVkIjp7InRva2VuIjoiMHhlOTFEMTUzRTBiNDE1MThBMkNlOERkM0Q3OTQ0RmE4NjM0NjNhOTdkIiwiYW1vdW50IjoiOTAwMDAwMDAwMDAwMDAwMDAwMCJ9LCJub25jZSI6IjYyOTc2MjY4MDU3NjQ1MTA0ODc3MTI4NDU3MTU1NDgwNTU5NzU1OTQwMjA4MzExMDQ3Mjc1Njc2NjAyNDI3NzQwODY1NzE0MDkxMzAwIiwiZGVhZGxpbmUiOiIxMTU3OTIwODkyMzczMTYxOTU0MjM1NzA5ODUwMDg2ODc5MDc4NTMyNjk5ODQ2NjU2NDA1NjQwMzk0NTc1ODQwMDc5MTMxMjk2Mzk5MzUifSwidHJhbnNmZXJEZXRhaWxzIjp7InRvIjoiMHhmMzlGZDZlNTFhYWQ4OEY2RjRjZTZhQjg4MjcyNzljZmZGYjkyMjY2IiwicmVxdWVzdGVkQW1vdW50IjoiOTAwMDAwMDAwMDAwMDAwMDAwMCJ9LCJvd25lciI6IjB4NzA5OTc5NzBDNTE4MTJkYzNBMDEwQzdkMDFiNTBlMGQxN2RjNzlDOCIsInNpZ25hdHVyZSI6IjB4N2RhZjExM2E1MDRmNjFjOTkwODRkYzZkYWVlNmRkMWRmOGEzYjhiMzllNTQ3ZWRhYjEyM2E3NDE2MGE1ZWE0NjBkODI4N2ZhYzUwOWFhNzkzZmE2NzkzZGU5ODliZWE5ODhjYzc0MDI0YTlmZDI2MDIyNjZhNDNmODUwOWFhMmQxYiIsIm5ldHdvcmtJZCI6MzEzMzd9XQ=="
);
cy.wait(2000);

cy.wait("@listGiftCards");

cy.get("#gift-cards").should("exist").and("include.text", "Your gift card");
cy.get(".gift-card.redeem-code > h3").eq(0).should("have.text", "Your redeem code");
cy.get(".gift-card.redeem-code > p").eq(0).should("have.text", "xxxxxxxxxxxx");
cy.get(".gift-card.redeem-code > p").eq(1).should("have.text", "xxxxxxxxxxxx");
cy.get(".gift-card.redeem-code > p").eq(2).should("have.text", "xxxxxxxxxxxx");
cy.get(".gift-card.redeem-code > .buttons > #reveal-btn").invoke("click");

cy.get(".gift-card.redeem-code > h3").eq(0).should("have.text", "Your redeem code");
cy.get(".gift-card.redeem-code > p").should("exist");
cy.get(".gift-card.redeem-code > p").eq(0).should("not.have.text", "xxxxxxxxxxxx");
});
});

function setupStubs() {
const provider = new JsonRpcProvider("http://localhost:8545");
const signer = provider.getSigner(beneficiary);
const wallet = new Wallet(SENDER_PRIVATE_KEY, provider);

signer.signMessage = cy.stub().callsFake(async () => {
return "0x4d9f92f69898fd112748ff04c98e294cced4dbde80ac3cba42fb546538bf54ca0e3fbc3f94416813f8da58a4b26957b62bae66c48bf01ca1068af0f222bf18df1c";
});
stubEthereum(signer);

return { provider, signer, wallet };
}

function setupIntercepts() {
cy.intercept("POST", "*", (req) => {
// capturing the RPC optimization calls
if (req.body.method === "eth_getBlockByNumber") {
req.reply({
statusCode: 200,
body: cy.fixture("eth_getBlockByNumber.json"),
});
}
});

cy.intercept("POST", "https://wfzpewmlyiozupulbuur.supabase.co/rest/v1/*", {
statusCode: 200,
body: {},
});
cy.intercept("PATCH", "https://wfzpewmlyiozupulbuur.supabase.co/rest/v1/*", {
statusCode: 200,
body: {},
});
cy.intercept("GET", "https://wfzpewmlyiozupulbuur.supabase.co/rest/v1/*", {
statusCode: 200,
body: {},
});

cy.intercept({ method: "GET", url: "/list-gift-cards" }).as("listGiftCards");
}

function stubEthereum(signer: JsonRpcSigner) {
// Stubbing the ethereum object
cy.on("window:before:load", (win) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
((win as any).ethereum = {
isMetaMask: true,
enable: cy.stub().resolves(["0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"]),
request: cy.stub().callsFake(async (method) => providerFunctions(method)),
on: cy.stub().callsFake((event, cb) => {
if (event === "accountsChanged") {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(win as any).ethereum.onAccountsChanged = cb;
}
}),
autoRefreshOnNetworkChange: false,
chainId: "0x7a69",
selectedAddress: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
requestAccounts: cy.stub().resolves(["0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"]),
send: cy.stub().callsFake(async (method) => providerFunctions(method)),
getSigner: () => signer,
}),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
((win as any).signer = signer);
});
}

function providerFunctions(method: string) {
switch (method) {
case "eth_requestAccounts":
return ["0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"];
case "wallet_sendDomainMetadata":
return true;
case "wallet_addEthereumChain":
return true;
case "wallet_switchEthereumChain":
return true;
case "wallet_watchAsset":
return true;
case "eth_chainId":
return "0x7a69";
case "eth_accounts":
return ["0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"];
case "eth_signTypedData_v4":
return "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266";
case "eth_estimateGas":
return "0x7a69";
}
}

Cypress.Commands.add("getPermitUrl", (customPermitConfig: PermitConfig) => {
return generateERC20Permit(customPermitConfig);
});
2 changes: 1 addition & 1 deletion cypress/e2e/claim-portal-success.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe("Claims Portal Success", () => {
it("should successfully claim a permit", () => {
cy.get("#additionalDetails", { timeout: 15000 }).should("be.visible").invoke("click");

cy.get('table[data-make-claim="ok"]').should("exist").and("include.text", "337888.4 WXDAI");
cy.get('table[data-make-claim="ok"]').should("exist");

cy.get("button[id='make-claim']").invoke("click");

Expand Down
7 changes: 7 additions & 0 deletions cypress/e2e/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/// <reference types="cypress" />

declare namespace Cypress {
interface Chainable {
getPermitUrl(permitConfig: PermitConfig): Promise<string>;
}
}
2 changes: 1 addition & 1 deletion cypress/scripts/anvil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { spawn } from "child_process";

const url = "http://localhost:8545";

const anvil = spawn("anvil", ["--chain-id", "31337", "--fork-url", "https://gnosis.drpc.org", "--host", "127.0.0.1", "--port", "8545"], {
const anvil = spawn("anvil", ["--chain-id", "31337", "--fork-url", "wss://rpc.gnosischain.com/wss", "--host", "127.0.0.1", "--port", "8545"], {
stdio: "inherit",
});

Expand Down
65 changes: 65 additions & 0 deletions functions/get-order.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { Env, getAccessToken, getBaseUrl, commonHeaders } from "./helpers";
import { ReloadlyFailureResponse, ReloadlyGetTransactionResponse } from "./types";
import { validateEnvVars, validateRequestMethod } from "./validators";
import { AccessToken } from "./types";

export const onRequest: PagesFunction<Env> = async (ctx) => {
try {
validateRequestMethod(ctx.request.method, "GET");
validateEnvVars(ctx);

const { searchParams } = new URL(ctx.request.url);
const orderId = searchParams.get("orderId");

if (!orderId) {
throw new Error(`Invalid query parameters: ${{ orderId }}`);
}

const accessToken = await getAccessToken(ctx.env);

const reloadlyTransaction = await getTransactionFromOrderId(orderId, accessToken);

if (!reloadlyTransaction) {
return Response.json("Order not found.", { status: 404 });
} else if (reloadlyTransaction.status && reloadlyTransaction.status == "SUCCESSFUL") {
return Response.json(reloadlyTransaction, { status: 200 });
} else {
return Response.json({ message: "There is no successful transaction for given order ID." }, { status: 404 });
}
} catch (error) {
console.error("There was an error while processing your request.", error);
return Response.json({ message: "There was an error while processing your request." }, { status: 500 });
}
};

export const getTransactionFromOrderId = async (orderId: string, accessToken: AccessToken) => {
const nowFormatted = new Date().toISOString().replace("T", " ").substring(0, 19); //// yyyy-mm-dd HH:mm:ss
const oneYearAgo = new Date(new Date().setFullYear(new Date().getFullYear() - 1));
const oneYearAgoFormatted = oneYearAgo.toISOString().replace("T", " ").substring(0, 19);

const url = `${getBaseUrl(accessToken.isSandbox)}/reports/transactions?size=1&page=1&customIdentifier=${orderId}&startDate=${oneYearAgoFormatted}&endDate=${nowFormatted}`;
console.log(`Retrieving transaction from ${url}`);
const options = {
method: "GET",
headers: {
...commonHeaders,
Authorization: `Bearer ${accessToken.token}`,
},
};

const response = await fetch(url, options);
const responseJson = await response.json();

console.log("Response status", response.status);
console.log(`Response from ${url}`, responseJson);

if (response.status != 200) {
throw new Error(
`Error from Reloadly API: ${JSON.stringify({
status: response.status,
message: (responseJson as ReloadlyFailureResponse).message,
})}`
);
}
return (responseJson as ReloadlyGetTransactionResponse).content[0];
};
Loading
Loading