import { Hash, Hex } from 'ox' import { tempoMainnet } from 'viem/tempo/chains' import * as FundingDepositAddresses from '../../../db/tables/fundingDepositAddresses.js' import * as FundingIdempotencyTable from '../../../db/tables/fundingIdempotency.js' import * as Cache from '../../../internal/Cache.js' import * as Cursor from '../../../internal/Cursor.js' import * as FundingDeposit from '../../../internal/funding/Deposit.js' import * as FundingDepositAddress from '../../../internal/funding/DepositAddress.js' import * as FundingProvider from '../../../internal/funding/Provider.js' import * as Idempotency from '../../../internal/Idempotency.js' import * as Across from '../../../internal/funding/providers/across.js' import * as Relay from '../../../internal/funding/providers/relay.js' import * as Rhino from '../../../internal/funding/providers/rhino.js' import * as Squid from '../../../internal/funding/providers/squid.js' import * as Symbiosis from '../../../internal/funding/providers/symbiosis.js' import type * as Log from '../../../internal/Log.js' import * as TestApp from '../../../../test/App.js' import * as TestFunding from '../../../../test/Funding.js' import * as Funding from './deposit-addresses.js' const db = TestApp.database() const relayApiKey = process.env.RELAY_API_KEY const providers = [ Across.across({ apiKey: 'across-api-key', integratorId: '0xdead', userAddress: '0x1111111111111111111111111111111111111111', }), Relay.relay({ userAddresses: TestFunding.relayQuoteUsers }), Rhino.rhino(), Squid.squid({ integratorId: 'squid-integrator-id', userAddress: '0x1111111111111111111111111111111111111111', }), Symbiosis.symbiosis({ userAddress: '0x1111111111111111111111111111111111111111' }), ] as const beforeAll(() => TestFunding.publish(db)) function create(options: TestApp.create.Options = {}) { return TestApp.create({ ...options, db }) } type ContractResponse = { $ref?: string | undefined content?: Record | undefined } type JsonSchema = { $ref?: string | undefined properties?: Record | undefined } type ComponentSpec = { components: { schemas: Record } } function dereference(spec: ComponentSpec, schema: JsonSchema): JsonSchema { if (!schema.$ref) return schema const name = schema.$ref.split('/').at(-1)! return spec.components.schemas[name]! } test('publishes generator-ready funding deposit contracts', async () => { const spec = await (await create({ auth: false }).request('/openapi.json')).json() const depositAddressPath = Object.keys(spec.paths).find( (path) => path.includes('/v1/funding/deposit-addresses/{') && !path.endsWith('/reconcile'), )! const depositPath = Object.keys(spec.paths).find((path) => path.includes('/v1/funding/deposits/{'), )! const reconcilePath = Object.keys(spec.paths).find((path) => path.endsWith('/reconcile'))! const operations = { createAddress: spec.paths['/v1/funding/deposit-addresses'].post, getAddress: spec.paths[depositAddressPath].get, getDeposit: spec.paths[depositPath].get, listAddresses: spec.paths['/v1/funding/deposit-addresses'].get, listDeposits: spec.paths['/v1/funding/deposits'].get, reconcileAddress: spec.paths[reconcilePath].post, } const summarize = (operation: (typeof operations)[keyof typeof operations]) => ({ errors: Object.fromEntries( (Object.entries(operation.responses) as [string, ContractResponse][]) .filter(([status]) => Number(status) >= 400) .map(([status, response]) => [ status, response.$ref ?? response.content?.['application/json']?.schema, ]), ), operationId: operation.operationId, request: operation.requestBody?.content['application/json'].schema, response: operation.responses[200]?.content?.['application/json']?.schema ?? operation.responses[202]?.content?.['application/json']?.schema, }) expect({ components: [ 'CreateFundingDepositAddressRequest', 'CreateFundingDepositAddressResponse', 'CreatedFundingDepositAddress', 'FundingDeposit', 'FundingDepositAddress', 'FundingDepositAddressList', 'FundingDepositList', 'FundingDepositStatusReason', ].filter((name) => spec.components.schemas[name]), formats: { addressCreatedAt: spec.components.schemas.FundingDepositAddress.properties.createdAt.format, addressUpdatedAt: spec.components.schemas.FundingDepositAddress.properties.updatedAt.format, depositCreatedAt: spec.components.schemas.FundingDeposit.properties.createdAt.format, depositUpdatedAt: spec.components.schemas.FundingDeposit.properties.updatedAt.format, }, models: { address: { destinationChain: spec.components.schemas.FundingDepositAddress.properties.destinationChain, destinationToken: spec.components.schemas.FundingDepositAddress.properties.destinationToken, provider: spec.components.schemas.FundingDepositAddress.properties.provider, sourceChain: spec.components.schemas.FundingDepositAddress.properties.sourceChain, sourceToken: spec.components.schemas.FundingDepositAddress.properties.sourceToken, }, addressList: spec.components.schemas.FundingDepositAddressList.properties.data.items, createResponse: spec.components.schemas.CreateFundingDepositAddressResponse.anyOf, createdAddress: { feeToken: dereference( spec, spec.components.schemas.CreatedFundingDepositAddress.properties.fees.items, ).properties!['token'], quote: spec.components.schemas.CreatedFundingDepositAddress.properties.quote, }, deposit: { destinationChain: spec.components.schemas.FundingDeposit.properties.destinationChain, destinationToken: spec.components.schemas.FundingDeposit.properties.destinationToken, provider: spec.components.schemas.FundingDeposit.properties.provider, sourceChain: spec.components.schemas.FundingDeposit.properties.sourceChain, sourceToken: spec.components.schemas.FundingDeposit.properties.sourceToken, statusReason: spec.components.schemas.FundingDeposit.properties.statusReason, }, depositList: spec.components.schemas.FundingDepositList.properties.data.items, }, operations: { createAddress: summarize(operations.createAddress), getAddress: summarize(operations.getAddress), getDeposit: summarize(operations.getDeposit), listAddresses: summarize(operations.listAddresses), listDeposits: summarize(operations.listDeposits), reconcileAddress: summarize(operations.reconcileAddress), }, sharedErrorCodes: { addressNotActive: spec.components.schemas.FundingDepositAddressNotActiveError.properties.error.properties.code .enum, addressNotAvailable: spec.components.schemas.DepositAddressNotAvailableError.properties.error.properties.code .enum, addressNotFound: spec.components.schemas.FundingDepositAddressNotFoundError.properties.error.properties.code .enum, createInvalid: spec.components.schemas.ApiKeyMalformedOrBodyInvalidOrIdempotencyKeyRequiredError.properties .error.properties.code.enum, depositNotFound: spec.components.schemas.FundingDepositNotFoundError.properties.error.properties.code.enum, idempotencyConflict: spec.components.schemas.IdempotencyConflictOrIdempotencyInProgressError.properties.error .properties.code.enum, notImplemented: spec.components.schemas.NotImplemented501Error.properties.error.properties.code.enum, parametersInvalid: spec.components.schemas.ApiKeyMalformedOrParamInvalidError.properties.error.properties.code .enum, queryInvalid: spec.components.schemas.ApiKeyMalformedOrQueryInvalidError.properties.error.properties.code .enum, }, }).toMatchInlineSnapshot(` { "components": [ "CreateFundingDepositAddressRequest", "CreateFundingDepositAddressResponse", "CreatedFundingDepositAddress", "FundingDeposit", "FundingDepositAddress", "FundingDepositAddressList", "FundingDepositList", "FundingDepositStatusReason", ], "formats": { "addressCreatedAt": "date-time", "addressUpdatedAt": "date-time", "depositCreatedAt": "date-time", "depositUpdatedAt": "date-time", }, "models": { "address": { "destinationChain": { "$ref": "#/components/schemas/FundingChain", }, "destinationToken": { "$ref": "#/components/schemas/FundingToken", }, "provider": { "$ref": "#/components/schemas/FundingProvider", }, "sourceChain": { "$ref": "#/components/schemas/FundingChain", }, "sourceToken": { "$ref": "#/components/schemas/FundingToken", }, }, "addressList": { "$ref": "#/components/schemas/FundingDepositAddress", }, "createResponse": [ { "$ref": "#/components/schemas/CreatedFundingDepositAddress", }, { "$ref": "#/components/schemas/FundingDepositAddress", }, ], "createdAddress": { "feeToken": { "$ref": "#/components/schemas/FundingToken", }, "quote": { "$ref": "#/components/schemas/FundingQuoteDetails", }, }, "deposit": { "destinationChain": { "$ref": "#/components/schemas/FundingChain", }, "destinationToken": { "$ref": "#/components/schemas/FundingToken", }, "provider": { "$ref": "#/components/schemas/FundingProvider", }, "sourceChain": { "$ref": "#/components/schemas/FundingChain", }, "sourceToken": { "$ref": "#/components/schemas/FundingToken", }, "statusReason": { "$ref": "#/components/schemas/FundingDepositStatusReason", }, }, "depositList": { "$ref": "#/components/schemas/FundingDeposit", }, }, "operations": { "createAddress": { "errors": { "400": { "$ref": "#/components/schemas/ApiKeyMalformedOrBodyInvalidOrIdempotencyKeyRequiredError", }, "401": { "$ref": "#/components/schemas/AuthenticationError", }, "403": { "$ref": "#/components/schemas/ForbiddenError", }, "404": { "$ref": "#/components/schemas/DepositAddressNotAvailableError", }, "409": { "$ref": "#/components/schemas/IdempotencyConflictOrIdempotencyInProgressError", }, "429": "#/components/responses/RateLimited", "500": "#/components/responses/InternalError", "502": { "$ref": "#/components/schemas/UpstreamError", }, "504": "#/components/responses/RequestTimeout", }, "operationId": "createFundingDepositAddress", "request": { "$ref": "#/components/schemas/CreateFundingDepositAddressRequest", }, "response": { "$ref": "#/components/schemas/CreateFundingDepositAddressResponse", }, }, "getAddress": { "errors": { "400": { "$ref": "#/components/schemas/ApiKeyMalformedOrParamInvalidError", }, "401": { "$ref": "#/components/schemas/AuthenticationError", }, "403": { "$ref": "#/components/schemas/ForbiddenError", }, "404": { "$ref": "#/components/schemas/FundingDepositAddressNotFoundError", }, "429": "#/components/responses/RateLimited", "500": "#/components/responses/InternalError", "502": { "$ref": "#/components/schemas/UpstreamError", }, "504": "#/components/responses/RequestTimeout", }, "operationId": "getFundingDepositAddress", "request": undefined, "response": { "$ref": "#/components/schemas/FundingDepositAddress", }, }, "getDeposit": { "errors": { "400": { "$ref": "#/components/schemas/ApiKeyMalformedOrParamInvalidError", }, "401": { "$ref": "#/components/schemas/AuthenticationError", }, "403": { "$ref": "#/components/schemas/ForbiddenError", }, "404": { "$ref": "#/components/schemas/FundingDepositNotFoundError", }, "429": "#/components/responses/RateLimited", "500": "#/components/responses/InternalError", "502": { "$ref": "#/components/schemas/UpstreamError", }, "504": "#/components/responses/RequestTimeout", }, "operationId": "getFundingDeposit", "request": undefined, "response": { "$ref": "#/components/schemas/FundingDeposit", }, }, "listAddresses": { "errors": { "400": { "$ref": "#/components/schemas/ApiKeyMalformedOrQueryInvalidError", }, "401": { "$ref": "#/components/schemas/AuthenticationError", }, "403": { "$ref": "#/components/schemas/ForbiddenError", }, "429": "#/components/responses/RateLimited", "500": "#/components/responses/InternalError", "502": { "$ref": "#/components/schemas/UpstreamError", }, "504": "#/components/responses/RequestTimeout", }, "operationId": "listFundingDepositAddresses", "request": undefined, "response": { "$ref": "#/components/schemas/FundingDepositAddressList", }, }, "listDeposits": { "errors": { "400": { "$ref": "#/components/schemas/ApiKeyMalformedOrQueryInvalidError", }, "401": { "$ref": "#/components/schemas/AuthenticationError", }, "403": { "$ref": "#/components/schemas/ForbiddenError", }, "429": "#/components/responses/RateLimited", "500": "#/components/responses/InternalError", "502": { "$ref": "#/components/schemas/UpstreamError", }, "504": "#/components/responses/RequestTimeout", }, "operationId": "listFundingDeposits", "request": undefined, "response": { "$ref": "#/components/schemas/FundingDepositList", }, }, "reconcileAddress": { "errors": { "400": { "$ref": "#/components/schemas/ApiKeyMalformedOrParamInvalidError", }, "401": { "$ref": "#/components/schemas/AuthenticationError", }, "403": { "$ref": "#/components/schemas/ForbiddenError", }, "404": { "$ref": "#/components/schemas/FundingDepositAddressNotFoundError", }, "409": { "$ref": "#/components/schemas/FundingDepositAddressNotActiveError", }, "429": "#/components/responses/RateLimited", "500": "#/components/responses/InternalError", "501": { "$ref": "#/components/schemas/NotImplemented501Error", }, "502": { "$ref": "#/components/schemas/UpstreamError", }, "504": "#/components/responses/RequestTimeout", }, "operationId": "reconcileFundingDepositAddress", "request": undefined, "response": undefined, }, }, "sharedErrorCodes": { "addressNotActive": [ "funding_deposit_address_not_active", ], "addressNotAvailable": [ "deposit_address_not_available", ], "addressNotFound": [ "funding_deposit_address_not_found", ], "createInvalid": [ "api_key_malformed", "body_invalid", "idempotency_key_required", ], "depositNotFound": [ "funding_deposit_not_found", ], "idempotencyConflict": [ "idempotency_conflict", "idempotency_in_progress", ], "notImplemented": [ "not_implemented", ], "parametersInvalid": [ "api_key_malformed", "param_invalid", ], "queryInvalid": [ "api_key_malformed", "query_invalid", ], }, } `) }) describe('POST /funding/deposit-addresses', () => { test('requires funding:write and an idempotency key', async () => { const app = transfersApp({ providers: [depositAddressProvider()] }) expect((await postDepositAddress(app, { headers: {} })).status).toBe(401) expect((await postDepositAddress(app, { key: fundingReader })).status).toBe(403) const response = await postDepositAddress(app, { headers: { authorization: `Bearer ${fundingWriter.token}` }, }) expect(response.status).toBe(400) expect(((await response.json()) as { error: { code: string } }).error.code).toBe( 'idempotency_key_required', ) }) test('requires a source amount', async () => { const { amount: _amount, ...body } = depositAddressBody const response = await postDepositAddress( transfersApp({ providers: [depositAddressProvider()] }), { body }, ) expect({ body: await response.json(), status: response.status }).toMatchInlineSnapshot( { body: { requestId: expect.any(String) }, }, ` { "body": { "error": { "code": "body_invalid", "details": [ { "message": "Invalid input: expected string, received undefined", "path": [ "amount", ], }, ], "message": "Check the request body and try again.", }, "requestId": Any, }, "status": 400, } `, ) }) test('creates a reusable address and persists private provider correlation', async () => { let seen: FundingProvider.createDepositAddress.Parameters | undefined const registered: FundingDepositAddress.Public[] = [] const app = transfersApp({ funding: { registerDepositAddress: async (address) => { registered.push(address) }, }, providers: [ depositAddressProvider('TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV', (input) => { seen = input }), ], }) const response = await postDepositAddress(app, { body: { ...depositAddressBody, destinationToken: 'usdt0', sourceToken: 'usdt' }, }) expect(response.status).toBe(200) expect(response.headers.get('cache-control')).toBe('no-store') const body = await TestApp.json(response, Funding.schema.createFundingDepositAddress.Response) expect(body).toMatchObject({ address: 'TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV', destinationToken: { symbol: 'USDT0' }, provider: { id: 'relay', name: 'Relay' }, recipient: depositAddressBody.recipient, refundAddress: depositAddressBody.refundAddress, sourceChain: { id: 'tron:0x2b6653dc' }, sourceToken: { symbol: 'USDT' }, status: 'active', }) expect(seen).toMatchObject({ recipient: depositAddressBody.recipient, refundAddress: depositAddressBody.refundAddress, }) const record = await FundingDepositAddresses.get(db, body.id) expect(record).toMatchObject({ deliveryStrategy: 'provider', providerOutputToken: body.destinationToken, providerRequestIds: ['relay_request_1'], providerState: { checkEndpoint: '/intents/status/v3?requestId=relay_request_1' }, }) expect(registered).toMatchInlineSnapshot( [ { createdAt: expect.any(String), id: expect.any(String), updatedAt: expect.any(String), }, ], ` [ { "address": "TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV", "createdAt": Any, "destinationChain": { "addressFormat": "hex", "id": "eip155:4217", "kind": "evm", "name": "Tempo", }, "destinationToken": { "address": "0x20c00000000000000000000014f22ca97301eb73", "currency": "USD", "decimals": 6, "name": "USDT0", "standard": "TIP-20", "symbol": "USDT0", "tokenKey": "eip155:4217/erc20:0x20c00000000000000000000014f22ca97301eb73", "verified": true, }, "id": Any, "provider": { "id": "relay", "name": "Relay", }, "recipient": "0x1111111111111111111111111111111111111111", "refundAddress": "TJRabPrwbZy45sbavfcjinPJC18kjpRTv8", "sourceChain": { "addressFormat": "base58check", "id": "tron:0x2b6653dc", "kind": "tron", "name": "Tron", }, "sourceToken": { "address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "currency": "USD", "decimals": 6, "name": "Tether USD", "standard": "TRC-20", "symbol": "USDT", "tokenKey": "tron:0x2b6653dc/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "verified": true, }, "status": "active", "subsidize": false, "updatedAt": Any, }, ] `, ) }) test('resolves token identifiers through the composed route', async () => { const app = transfersApp({ providers: [depositAddressProvider('T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb')], }) const identifiers = [ { destinationToken: 'usdt0', name: 'alias', sourceToken: 'usdt' }, { destinationToken: depositAddressBody.destinationToken, name: 'address', sourceToken: depositAddressBody.sourceToken, }, { destinationToken: 'eip155:4217/erc20:0x20c00000000000000000000014f22ca97301eb73', name: 'token key', sourceToken: 'tron:0x2b6653dc/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', }, ] as const const results = [] for (const identifier of identifiers) { const response = await postDepositAddress(app, { body: { ...depositAddressBody, destinationToken: identifier.destinationToken, recipient: `0x${'55'.repeat(20)}`, refundAddress: 'TD5gsCwxykWsLN9aPrq2TAfNjByuZKYp4E', sourceToken: identifier.sourceToken, }, }) const body = await TestApp.json(response, Funding.schema.createFundingDepositAddress.Response) results.push({ destinationToken: body.destinationToken.symbol, name: identifier.name, sourceToken: body.sourceToken.symbol, status: response.status, }) } expect(results).toMatchInlineSnapshot(` [ { "destinationToken": "USDT0", "name": "alias", "sourceToken": "USDT", "status": 200, }, { "destinationToken": "USDT0", "name": "address", "sourceToken": "USDT", "status": 200, }, { "destinationToken": "USDT0", "name": "token key", "sourceToken": "USDT", "status": 200, }, ] `) }) test('omits newly quoted terms from a matching reusable address', async () => { let calls = 0 const body = { ...depositAddressBody, refundAddress: 'TD5gsCwxykWsLN9aPrq2TAfNjByuZKYp4E' } const app = transfersApp({ providers: [ depositAddressProvider('TEdvoHEatmDKvTh3o9vBRB9Vdtbhn4QFhy', () => { calls += 1 }), ], }) const first = await TestApp.json( await postDepositAddress(app, { body, idempotencyKey: nextDepositAddressKey() }), Funding.schema.createFundingDepositAddress.Response, ) const second = await TestApp.json( await postDepositAddress(app, { body: { ...body, amount: '200000000' }, idempotencyKey: nextDepositAddressKey(), }), Funding.schema.createFundingDepositAddress.Response, ) if (!('sourceAmount' in first)) throw new Error('Expected newly provisioned terms.') expect({ calls, firstHasQuote: 'quote' in first, firstId: first.id, firstSourceAmount: first.sourceAmount.baseUnits, secondHasQuote: 'quote' in second, secondId: second.id, }).toMatchInlineSnapshot( { firstId: expect.any(String), secondId: expect.any(String), }, ` { "calls": 2, "firstHasQuote": true, "firstId": Any, "firstSourceAmount": "100000000", "secondHasQuote": false, "secondId": Any, } `, ) expect(second.id).toBe(first.id) }) test('stores subsidized addresses as a separate reusable identity', async () => { const inputs: FundingProvider.createDepositAddress.Parameters[] = [] const app = transfersApp({ providers: [ withCreateDepositAddress('relay', async (input) => { inputs.push(input) return { address: inputs.length === 1 ? `0x${'31'.repeat(20)}` : `0x${'32'.repeat(20)}`, correlation: { requestId: `relay_request_${inputs.length}` }, destinationAmount: '1000000', destinationAmountMin: '1000000', fees: [], sampledAt: '2026-08-04T00:00:00.000Z', } }), ], }) const body = { ...depositAddressBody, refundAddress: `0x${'33'.repeat(20)}`, sourceChain: 'base', sourceToken: '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2', } const standard = await TestApp.json( await postDepositAddress(app, { body }), Funding.schema.createFundingDepositAddress.Response, ) const subsidized = await TestApp.json( await postDepositAddress(app, { body: { ...body, subsidize: true } }), Funding.schema.createFundingDepositAddress.Response, ) expect({ distinct: standard.id !== subsidized.id, inputs: inputs.map(({ subsidize }) => subsidize), standard: standard.subsidize, subsidized: subsidized.subsidize, }).toMatchInlineSnapshot(` { "distinct": true, "inputs": [ false, true, ], "standard": false, "subsidized": true, } `) }) test('normalizes EVM accounts before provisioning and matching', async () => { const inputs: FundingProvider.createDepositAddress.Parameters[] = [] const recipient = '0xABcdEFABcdEFabcdEfAbCdefabcdeFABcDEFabCD' const refundAddress = '0x1234567890AbcdEF1234567890aBcdef12345678' const body = { ...depositAddressBody, recipient, refundAddress, sourceChain: 'base', sourceToken: '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2', } const app = transfersApp({ providers: [ depositAddressProvider(`0x${'99'.repeat(20)}`, (input) => { inputs.push(input) }), ], }) const first = await TestApp.json( await postDepositAddress(app, { body, idempotencyKey: nextDepositAddressKey() }), Funding.schema.createFundingDepositAddress.Response, ) const second = await TestApp.json( await postDepositAddress(app, { body: { ...body, recipient: recipient.toLowerCase(), refundAddress: refundAddress.toLowerCase(), }, idempotencyKey: nextDepositAddressKey(), }), Funding.schema.createFundingDepositAddress.Response, ) expect({ first: { recipient: first.recipient, refundAddress: first.refundAddress }, inputs: inputs.map(({ recipient, refundAddress }) => ({ recipient, refundAddress })), reused: first.id === second.id, second: { recipient: second.recipient, refundAddress: second.refundAddress }, }).toMatchInlineSnapshot(` { "first": { "recipient": "0xABcdEFABcdEFabcdEfAbCdefabcdeFABcDEFabCD", "refundAddress": "0x1234567890AbcdEF1234567890aBcdef12345678", }, "inputs": [ { "recipient": "0xABcdEFABcdEFabcdEfAbCdefabcdeFABcDEFabCD", "refundAddress": "0x1234567890AbcdEF1234567890aBcdef12345678", }, { "recipient": "0xABcdEFABcdEFabcdEfAbCdefabcdeFABcDEFabCD", "refundAddress": "0x1234567890AbcdEF1234567890aBcdef12345678", }, ], "reused": true, "second": { "recipient": "0xABcdEFABcdEFabcdEfAbCdefabcdeFABcDEFabCD", "refundAddress": "0x1234567890AbcdEF1234567890aBcdef12345678", }, } `) }) test('keeps the stored reusable address when the provider rotates addresses', async () => { const body = { ...depositAddressBody, recipient: `0x${'22'.repeat(20)}` } const first = await TestApp.json( await postDepositAddress( transfersApp({ providers: [depositAddressProvider('TGCAjMXComunWZEXCT1LPBdcYbDVuyexBv')], }), { body, idempotencyKey: nextDepositAddressKey() }, ), Funding.schema.createFundingDepositAddress.Response, ) let calls = 0 const app = transfersApp({ providers: [ depositAddressProvider('THkQfRopincF6emzbk6VMC7jTHqJ8MP8g7', () => { calls += 1 }), ], }) const idempotencyKey = nextDepositAddressKey() const response = await postDepositAddress(app, { body: { ...body, amount: '200000000' }, idempotencyKey, }) const second = await TestApp.json(response, Funding.schema.createFundingDepositAddress.Response) expect({ address: second.address, calls, hasQuote: 'quote' in second, reused: second.id === first.id, status: response.status, }).toMatchInlineSnapshot( { address: expect.any(String), }, ` { "address": Any, "calls": 1, "hasQuote": false, "reused": true, "status": 200, } `, ) expect(second.address).toBe(first.address) expect( await TestApp.json( await postDepositAddress(app, { body: { ...body, amount: '200000000' }, idempotencyKey, }), Funding.schema.createFundingDepositAddress.Response, ), ).toEqual(second) expect(calls).toBe(1) }) test('rejects a refund address from another chain', async () => { const response = await postDepositAddress( transfersApp({ providers: [depositAddressProvider()] }), { body: { ...depositAddressBody, refundAddress: `0x${'11'.repeat(20)}` } }, ) expect({ body: await response.json(), status: response.status }).toMatchInlineSnapshot( { body: { requestId: expect.any(String) }, }, ` { "body": { "error": { "code": "body_invalid", "message": "Invalid \`refundAddress\`.", }, "requestId": Any, }, "status": 400, } `, ) }) test('replays matching idempotent requests and rejects changed input', async () => { const body = { ...depositAddressBody, refundAddress: 'TKJebW6SdoJhgkKU13BeKCbrMzT6HeQhJ6' } const app = transfersApp({ providers: [depositAddressProvider('TLrtXaP4Yp1AGqrwQLGoHD5yGh4tTAvPbe')], }) const idempotencyKey = nextDepositAddressKey() const first = await postDepositAddress(app, { body, idempotencyKey }) const replay = await postDepositAddress(app, { body, idempotencyKey }) expect(replay.status).toBe(200) expect(await replay.json()).toEqual(await first.json()) const conflict = await postDepositAddress(app, { body: { ...depositAddressBody, refundAddress: 'TNR8TefgTphcrwQQodMxFDa6BPggc2CZeE' }, idempotencyKey, }) expect(conflict.status).toBe(409) expect(((await conflict.json()) as { error: { code: string } }).error.code).toBe( 'idempotency_conflict', ) }) test('defaults subsidize for legacy idempotency replays', async () => { const app = transfersApp({ providers: [depositAddressProvider(`0x${'45'.repeat(20)}`)], }) const requestBody = { ...depositAddressBody, refundAddress: `0x${'44'.repeat(20)}`, sourceChain: 'base', sourceToken: '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2', } const idempotencyKey = nextDepositAddressKey() const first = await postDepositAddress(app, { body: requestBody, idempotencyKey }) const response = await TestApp.json(first, Funding.schema.createFundingDepositAddress.Response) const { subsidize: _, ...legacy } = response await db.kysely .updateTable('funding_idempotency_requests') .set({ response: JSON.stringify(legacy) }) .where('apiKeyId', '=', fundingWriter.id) .where('keyHash', '=', Idempotency.inputHash(idempotencyKey)) .returningAll() .executeTakeFirstOrThrow() const replay = await postDepositAddress(app, { body: requestBody, idempotencyKey }) const response_replay = await TestApp.json( replay, Funding.schema.createFundingDepositAddress.Response, ) expect({ status: replay.status, subsidize: response_replay.subsidize }).toMatchInlineSnapshot(` { "status": 200, "subsidize": false, } `) }) test('preserves the idempotency fingerprint when subsidize is omitted', async () => { const idempotencyKey = nextDepositAddressKey() await FundingIdempotencyTable.claim(db, { apiKeyId: fundingWriter.id, keyHash: Idempotency.inputHash(idempotencyKey), requestHash: Idempotency.inputHash({ body: depositAddressBody, endpoint: 'POST /v1/funding/deposit-addresses', }), ttlMs: 60_000, }) const response = await postDepositAddress(transfersApp(), { idempotencyKey }) expect({ body: await response.json(), status: response.status }).toMatchInlineSnapshot( { body: { requestId: expect.any(String) }, }, ` { "body": { "error": { "code": "idempotency_in_progress", "message": "An equivalent funding deposit address creation is still running.", }, "requestId": Any, }, "status": 409, } `, ) }) test('includes the creation endpoint in the idempotency fingerprint', async () => { const idempotencyKey = nextDepositAddressKey() await FundingIdempotencyTable.claim(db, { apiKeyId: fundingWriter.id, keyHash: Idempotency.inputHash(idempotencyKey), requestHash: Idempotency.inputHash(depositAddressBody), ttlMs: 60_000, }) const response = await postDepositAddress( transfersApp({ providers: [depositAddressProvider()] }), { idempotencyKey }, ) expect(response.status).toBe(409) expect(((await response.json()) as { error: { code: string } }).error.code).toBe( 'idempotency_conflict', ) }) test('returns not available without a registered provider', async () => { const response = await postDepositAddress(transfersApp({ providers: [] })) expect(response.status).toBe(404) expect(((await response.json()) as { error: { code: string } }).error.code).toBe( 'deposit_address_not_available', ) }) test('reports unexpected provider failures', async () => { const entries: Log.Entry[] = [] const app = transfersApp({ logger: (entry) => { entries.push(entry) }, providers: [ withCreateDepositAddress('relay', async () => { throw new Error('upstream failed') }), ], }) const response = await postDepositAddress(app, { body: { ...depositAddressBody, refundAddress: 'T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb' }, }) expect(response.status).toBe(502) expect(((await response.json()) as { error: { code: string } }).error.code).toBe( 'upstream_error', ) expect(entries.at(-1)).toMatchObject({ provider: { failure: 'unknown', id: 'relay', operation: 'createDepositAddress', }, status: 502, }) }) }) describe('POST /webhooks/funding/relay', () => { test('authenticates and enqueues a bounded reconciliation hint', async () => { const secret = 'relay-webhook-secret' const address = await seedDepositAddress({ snapshot: TestFunding.depositAddressSnapshot({ provider: { id: 'relay', name: 'Relay' }, recipient: `0x${'99'.repeat(20)}`, }), }) const dispatched: FundingProvider.Webhook.receive.Dispatchable[] = [] const app = transfersApp({ providers: [ Relay.relay({ apiKey: secret, webhook: { db, dispatch: async (message) => { dispatched.push(message) }, }, }), ], }) const timestamp = String(Date.now()) const body = JSON.stringify({ data: { depositAddress: { address: address.address }, requestId: 'relay-child-request', status: 'pending', updatedAt: Number(timestamp) - 1_000, }, event: 'request.status.updated', timestamp: Number(timestamp), }) const signature = Hash.hmac256( Hex.fromString(secret), Hex.fromString(`${timestamp}.${body}`), ).slice(2) const response = await app.request('/webhooks/funding/relay', { body, headers: { 'x-signature-sha256': signature, 'x-signature-timestamp': timestamp, }, method: 'POST', }) expect({ dispatched, status: response.status }).toMatchInlineSnapshot( { dispatched: [ { webhookTiming: { enqueuedAt: expect.any(String), providerUpdatedAt: expect.any(String), receivedAt: expect.any(String), sentAt: expect.any(String), }, }, ], }, ` { "dispatched": [ { "addressId": "${address.id}", "requestId": "relay-child-request", "trigger": "webhook", "type": "funding:deposit-address:reconcile", "webhookTiming": { "enqueuedAt": Any, "providerStatus": "pending", "providerUpdatedAt": Any, "receivedAt": Any, "sentAt": Any, }, }, ], "status": 204, } `, ) }) test('rejects unauthenticated events', async () => { const app = transfersApp({ providers: [ Relay.relay({ apiKey: 'relay-webhook-secret', webhook: { db, dispatch: async () => {} }, }), ], }) const response = await app.request('/webhooks/funding/relay', { body: '{}', method: 'POST', }) expect(response.status).toMatchInlineSnapshot('401') }) }) describe.skipIf(!relayApiKey)('POST /funding/deposit-addresses (relay)', () => { test('provisions and persists a reusable address through Relay', async () => { const app = transfersApp({ providers: [Relay.relay({ apiKey: relayApiKey })], }) const response = await postDepositAddress(app, { body: { ...depositAddressBody, recipient: `0x${'77'.repeat(20)}` }, }) expect(response.status).toBe(200) const body = await TestApp.json(response, Funding.schema.createFundingDepositAddress.Response) expect(body).toMatchInlineSnapshot( { address: expect.any(String), createdAt: expect.any(String), destinationAmount: { baseUnits: expect.any(String), formatted: expect.any(String), }, destinationAmountMin: { baseUnits: expect.any(String), formatted: expect.any(String), }, fees: expect.any(Array), id: expect.any(String), quote: { sampledAt: expect.any(String) }, updatedAt: expect.any(String), }, ` { "address": Any, "createdAt": Any, "destinationAmount": { "baseUnits": Any, "currency": "USD", "decimals": 6, "formatted": Any, }, "destinationAmountMin": { "baseUnits": Any, "currency": "USD", "decimals": 6, "formatted": Any, }, "destinationChain": { "addressFormat": "hex", "id": "eip155:4217", "kind": "evm", "name": "Tempo", }, "destinationToken": { "address": "0x20c00000000000000000000014f22ca97301eb73", "currency": "USD", "decimals": 6, "name": "USDT0", "standard": "TIP-20", "symbol": "USDT0", "tokenKey": "eip155:4217/erc20:0x20c00000000000000000000014f22ca97301eb73", "verified": true, }, "fees": Any, "id": Any, "provider": { "id": "relay", "name": "Relay", }, "quote": { "sampledAt": Any, }, "recipient": "0x7777777777777777777777777777777777777777", "refundAddress": "TJRabPrwbZy45sbavfcjinPJC18kjpRTv8", "sourceAmount": { "baseUnits": "100000000", "currency": "USD", "decimals": 6, "formatted": "100", }, "sourceChain": { "addressFormat": "base58check", "id": "tron:0x2b6653dc", "kind": "tron", "name": "Tron", }, "sourceToken": { "address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "currency": "USD", "decimals": 6, "name": "Tether USD", "standard": "TRC-20", "symbol": "USDT", "tokenKey": "tron:0x2b6653dc/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "verified": true, }, "status": "active", "subsidize": false, "updatedAt": Any, } `, ) const record = await FundingDepositAddresses.get(db, body.id) expect(record).toMatchInlineSnapshot( { address: expect.any(String), createdAt: expect.any(String), id: expect.any(String), nextPollAt: expect.any(String), providerRequestIds: [expect.any(String)], providerState: expect.any(Object), snapshot: { address: expect.any(String) }, updatedAt: expect.any(String), }, ` { "address": Any, "apiKeyId": "key_funding_writer", "createdAt": Any, "deliveryStrategy": "provider", "destinationTokenKey": "eip155:4217/erc20:0x20c00000000000000000000014f22ca97301eb73", "environment": "production", "id": Any, "lastPolledAt": null, "nextPollAt": Any, "orgId": "org_funding", "pollFailureCount": 0, "pollLeaseUntil": null, "pollLeaseVersion": 0, "projectId": null, "providerId": "relay", "providerOutputToken": { "address": "0x20c00000000000000000000014f22ca97301eb73", "currency": "USD", "decimals": 6, "name": "USDT0", "standard": "TIP-20", "symbol": "USDT0", "tokenKey": "eip155:4217/erc20:0x20c00000000000000000000014f22ca97301eb73", "verified": true, }, "providerRequestIds": [ Any, ], "providerState": Any, "recipient": "0x7777777777777777777777777777777777777777", "refundAddress": "TJRabPrwbZy45sbavfcjinPJC18kjpRTv8", "snapshot": { "address": Any, "destinationChain": { "addressFormat": "hex", "id": "eip155:4217", "kind": "evm", "name": "Tempo", }, "destinationToken": { "address": "0x20c00000000000000000000014f22ca97301eb73", "currency": "USD", "decimals": 6, "name": "USDT0", "standard": "TIP-20", "symbol": "USDT0", "tokenKey": "eip155:4217/erc20:0x20c00000000000000000000014f22ca97301eb73", "verified": true, }, "provider": { "id": "relay", "name": "Relay", }, "recipient": "0x7777777777777777777777777777777777777777", "refundAddress": "TJRabPrwbZy45sbavfcjinPJC18kjpRTv8", "sourceChain": { "addressFormat": "base58check", "id": "tron:0x2b6653dc", "kind": "tron", "name": "Tron", }, "sourceToken": { "address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "currency": "USD", "decimals": 6, "name": "Tether USD", "standard": "TRC-20", "symbol": "USDT", "tokenKey": "tron:0x2b6653dc/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "verified": true, }, "subsidize": false, }, "sourceChainId": "tron:0x2b6653dc", "sourceTokenKey": "tron:0x2b6653dc/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "status": "active", "subsidize": false, "updatedAt": Any, "version": 1, } `, ) }) }) describe('GET /funding/deposit-addresses', () => { test('pages organization addresses and narrows project-attributed keys', async () => { const app = transfersApp() const first = await seedDepositAddress({ orgId: fundingAddressListReader.orgId }) const second = await seedDepositAddress({ orgId: fundingAddressListReader.orgId }) const third = await seedDepositAddress({ orgId: fundingAddressListReader.orgId }) const project = await seedDepositAddress({ orgId: fundingAddressListReader.orgId, projectId: fundingAddressListProjectReader.projectId, }) const sibling = await seedDepositAddress({ orgId: fundingAddressListReader.orgId, projectId: 'prj_funding_address_list_sibling', }) const sixth = await seedDepositAddress({ orgId: fundingAddressListReader.orgId }) await seedDepositAddress({ orgId: fundingForeign.orgId }) await seedDepositAddress({ environment: 'sandbox', orgId: fundingAddressListReader.orgId, }) const path = '/v1/funding/deposit-addresses' expect((await app.request(path)).status).toBe(401) expect((await app.request(path, as(TestApp.key))).status).toBe(403) const response = await app.request(`${path}?limit=5`, as(fundingAddressListReader)) expect(response.status).toBe(200) expect({ cacheControl: response.headers.get('cache-control'), etag: response.headers.get('etag'), vary: response.headers.get('vary'), }).toEqual({ cacheControl: 'no-store', etag: null, vary: 'Accept-Encoding, Authorization, Tempo-API-Key, X-API-Key', }) const body = await TestApp.json(response, Funding.schema.listFundingDepositAddresses.Response) expect(body.data.map((address) => address.id)).toEqual([ sixth.id, sibling.id, project.id, third.id, second.id, ]) expect(body.nextCursor).toBe(Cursor.encode([second.createdAt, second.id])) const next = await TestApp.json( await app.request(`${path}?limit=5&cursor=${body.nextCursor}`, as(fundingAddressListReader)), Funding.schema.listFundingDepositAddresses.Response, ) expect(next.data.map((address) => address.id)).toEqual([first.id]) expect(next.nextCursor).toBeNull() const projectBody = await TestApp.json( await app.request(path, as(fundingAddressListProjectReader)), Funding.schema.listFundingDepositAddresses.Response, ) expect(projectBody.data.map((address) => address.id)).toEqual([project.id]) }) }) describe('GET /funding/deposit-addresses/:id', () => { test('requires funding:read and returns the owned address', async () => { const app = transfersApp() const record = await seedDepositAddress() const path = `/v1/funding/deposit-addresses/${record.id}` expect((await app.request(path)).status).toBe(401) expect((await app.request(path, as(TestApp.key))).status).toBe(403) const response = await app.request(path, as(fundingReader)) expect(response.status).toBe(200) expect({ cacheControl: response.headers.get('cache-control'), etag: response.headers.get('etag'), }).toMatchInlineSnapshot(` { "cacheControl": "no-store", "etag": null, } `) expect(response.headers.get('vary')).toBe( 'Accept-Encoding, Authorization, Tempo-API-Key, X-API-Key', ) const body = await TestApp.json(response, Funding.schema.getFundingDepositAddress.Response) expect(body).toEqual(FundingDepositAddress.toPublic(record)) expect(body).not.toHaveProperty('providerOutputToken') expect(body).not.toHaveProperty('providerRequestIds') }) test('hides foreign, project-inaccessible, and absent addresses', async () => { const app = transfersApp() const record = await seedDepositAddress() const path = `/v1/funding/deposit-addresses/${record.id}` for (const key of [fundingForeign, fundingProjectReader]) { const response = await app.request(path, as(key)) expect(response.status).toBe(404) expect(((await response.json()) as { error: { code: string } }).error.code).toBe( 'funding_deposit_address_not_found', ) } const absent = await app.request( '/v1/funding/deposit-addresses/fda_000000000000000_000000000000000000000000', as(fundingReader), ) expect(absent.status).toBe(404) }) }) describe('POST /funding/deposit-addresses/:id/reconcile', () => { test('requires funding:write and queues the owned active address', async () => { const dispatched: FundingProvider.Webhook.receive.Dispatchable[] = [] const app = transfersApp({ funding: { dispatchDepositReconciliation: async (message) => { dispatched.push(message) }, }, }) const record = await seedDepositAddress() const path = `/v1/funding/deposit-addresses/${record.id}/reconcile` expect((await app.request(path, { method: 'POST' })).status).toBe(401) expect((await app.request(path, { ...as(fundingReader), method: 'POST' })).status).toBe(403) const response = await app.request(path, { ...as(fundingWriter), method: 'POST' }) expect({ body: await response.text(), cacheControl: response.headers.get('cache-control'), dispatched, rateLimit: { limit: response.headers.get('ratelimit-limit'), remaining: response.headers.get('ratelimit-remaining'), scope: response.headers.get('ratelimit-scope'), }, status: response.status, vary: response.headers.get('vary'), }).toMatchInlineSnapshot(` { "body": "", "cacheControl": "no-store", "dispatched": [ { "addressId": "${record.id}", "trigger": "manual", "type": "funding:deposit-address:reconcile", }, ], "rateLimit": { "limit": "10", "remaining": "9", "scope": "funding:write", }, "status": 202, "vary": "Accept-Encoding, Authorization, Tempo-API-Key", } `) expect(await FundingDepositAddresses.get(db, record.id)).toEqual(record) }) test('hides foreign, project-inaccessible, and absent addresses', async () => { const dispatched: FundingProvider.Webhook.receive.Dispatchable[] = [] const app = transfersApp({ funding: { dispatchDepositReconciliation: async (message) => { dispatched.push(message) }, }, }) const record = await seedDepositAddress() const path = `/v1/funding/deposit-addresses/${record.id}/reconcile` for (const key of [fundingForeignWriter, fundingProjectWriter]) { const response = await app.request(path, { ...as(key), method: 'POST' }) expect(response.status).toBe(404) expect(((await response.json()) as { error: { code: string } }).error.code).toBe( 'funding_deposit_address_not_found', ) } const absent = await app.request( '/v1/funding/deposit-addresses/fda_000000000000000_000000000000000000000000/reconcile', { ...as(fundingWriter), method: 'POST' }, ) expect(absent.status).toBe(404) expect(dispatched).toEqual([]) }) test('rejects inactive addresses and unavailable reconciliation', async () => { const dispatched: FundingProvider.Webhook.receive.Dispatchable[] = [] const configured = transfersApp({ funding: { dispatchDepositReconciliation: async (message) => { dispatched.push(message) }, }, }) const record = await seedDepositAddress() const transition = await FundingDepositAddress.transition(db, { expectedVersion: record.version, id: record.id, status: 'action-required', }) expect(transition.type).toBe('applied') const inactive = await configured.request( `/v1/funding/deposit-addresses/${record.id}/reconcile`, { ...as(fundingWriter), method: 'POST' }, ) expect({ code: ((await inactive.json()) as { error: { code: string } }).error.code, status: inactive.status, }).toEqual({ code: 'funding_deposit_address_not_active', status: 409 }) const active = await seedDepositAddress() const unavailable = await transfersApp().request( `/v1/funding/deposit-addresses/${active.id}/reconcile`, { ...as(fundingWriter), method: 'POST' }, ) expect({ code: ((await unavailable.json()) as { error: { code: string } }).error.code, status: unavailable.status, }).toEqual({ code: 'not_implemented', status: 501 }) expect(dispatched).toEqual([]) }) test('returns an upstream error when the queue rejects the message', async () => { const app = transfersApp({ funding: { dispatchDepositReconciliation: async () => { throw new Error('queue unavailable') }, }, }) const record = await seedDepositAddress() const response = await app.request(`/v1/funding/deposit-addresses/${record.id}/reconcile`, { ...as(fundingWriter), method: 'POST', }) expect({ code: ((await response.json()) as { error: { code: string } }).error.code, status: response.status, }).toEqual({ code: 'upstream_error', status: 502 }) }) }) describe('GET /funding/deposits?depositAddress', () => { test('pages deposits newest-first under an owned address', async () => { const app = transfersApp() const address = await seedDepositAddress({ snapshot: TestFunding.depositAddressSnapshot({ address: 'TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE', provider: { id: 'relay_list_deposit_address', name: 'Relay' }, recipient: `0x${'41'.repeat(20)}`, }), }) const first = await seedDeposit(address) const second = await seedDeposit(address) const third = await seedDeposit(address) const fourth = await seedDeposit(address) const fifth = await seedDeposit(address) const sixth = await seedDeposit(address) const response = await app.request( `/v1/funding/deposits?depositAddress=${address.address}&limit=5`, as(fundingReader), ) expect(response.status).toBe(200) expect({ cacheControl: response.headers.get('cache-control'), etag: response.headers.get('etag'), }).toMatchInlineSnapshot(` { "cacheControl": "no-store", "etag": null, } `) const body = await TestApp.json(response, Funding.schema.listFundingDeposits.Response) expect(body.data.map((deposit) => deposit.id)).toEqual([ sixth.id, fifth.id, fourth.id, third.id, second.id, ]) expect(body.nextCursor).toBe(Cursor.encode([second.createdAt, second.id])) const next = await TestApp.json( await app.request( `/v1/funding/deposits?depositAddress=${address.address}&limit=5&cursor=${body.nextCursor}`, as(fundingReader), ), Funding.schema.listFundingDeposits.Response, ) expect(next.data.map((deposit) => deposit.id)).toEqual([first.id]) expect(next.nextCursor).toBeNull() }) test('returns a provider-observed deposit before source verification', async () => { const app = transfersApp() const address = await seedDepositAddress({ snapshot: TestFunding.depositAddressSnapshot({ address: 'TF17BgPaZYbz8oxbjhriubPDsA7ArKoLX3', provider: { id: 'relay_observed', name: 'Relay' }, recipient: `0x${'31'.repeat(20)}`, }), }) const sourceTransactionHash = `0x${'ab'.repeat(32)}` await FundingDeposit.create(db, { now: new Date('2026-01-04T00:00:00.000Z'), providerRequestId: 'relay-observed-request', snapshot: { depositAddressId: address.id, destinationChain: address.snapshot.destinationChain, destinationToken: address.snapshot.destinationToken, provider: address.snapshot.provider, recipient: address.recipient, refundAddress: address.refundAddress, sourceChain: address.snapshot.sourceChain, sourceToken: address.snapshot.sourceToken, sourceTransactionHashes: [sourceTransactionHash], }, sourceTransactionHash, }) const response = await app.request( `/v1/funding/deposits?depositAddress=${address.address}`, as(fundingReader), ) expect(response.status).toBe(200) const body = await TestApp.json(response, Funding.schema.listFundingDeposits.Response) expect(body).toMatchInlineSnapshot( { data: [ { createdAt: expect.any(String), depositAddressId: expect.any(String), id: expect.any(String), updatedAt: expect.any(String), }, ], }, ` { "data": [ { "createdAt": Any, "depositAddressId": Any, "destinationChain": { "addressFormat": "hex", "id": "eip155:4217", "kind": "evm", "name": "Tempo", }, "destinationToken": { "address": "0x20c00000000000000000000014f22ca97301eb73", "currency": "USD", "decimals": 6, "name": "USDT0", "standard": "TIP-20", "symbol": "USDT0", "tokenKey": "eip155:4217/erc20:0x20c00000000000000000000014f22ca97301eb73", "verified": true, }, "id": Any, "provider": { "id": "relay_observed", "name": "Relay", }, "recipient": "0x3131313131313131313131313131313131313131", "refundAddress": "TJRabPrwbZy45sbavfcjinPJC18kjpRTv8", "sourceChain": { "addressFormat": "base58check", "id": "tron:0x2b6653dc", "kind": "tron", "name": "Tron", }, "sourceToken": { "address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "currency": "USD", "decimals": 6, "name": "Tether USD", "standard": "TRC-20", "symbol": "USDT", "tokenKey": "tron:0x2b6653dc/trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "verified": true, }, "sourceTransactionHashes": [ "0xabababababababababababababababababababababababababababababababab", ], "status": "detected", "updatedAt": Any, }, ], "nextCursor": null, } `, ) }) test('hides a foreign deposit address', async () => { const app = transfersApp() const address = await seedDepositAddress({ orgId: fundingForeign.orgId, snapshot: TestFunding.depositAddressSnapshot({ address: 'TWd4WrZ9wn84f5x1hZhL4DHvk738ns5jwb', provider: { id: 'relay_foreign_deposit_address', name: 'Relay' }, recipient: `0x${'42'.repeat(20)}`, }), }) await seedDeposit(address) const response = await app.request( `/v1/funding/deposits?depositAddress=${address.address}`, as(fundingReader), ) expect(response.status).toBe(200) expect(await TestApp.json(response, Funding.schema.listFundingDeposits.Response)).toEqual({ data: [], nextCursor: null, }) }) }) describe('GET /funding/deposits', () => { test('pages organization deposits and narrows project-attributed keys', async () => { const app = transfersApp() const firstAddress = await seedDepositAddress({ orgId: fundingDepositListReader.orgId }) const secondAddress = await seedDepositAddress({ orgId: fundingDepositListReader.orgId }) const thirdAddress = await seedDepositAddress({ orgId: fundingDepositListReader.orgId }) const projectAddress = await seedDepositAddress({ orgId: fundingDepositListReader.orgId, projectId: fundingDepositListProjectReader.projectId, }) const siblingAddress = await seedDepositAddress({ orgId: fundingDepositListReader.orgId, projectId: 'prj_funding_deposit_list_sibling', }) const sixthAddress = await seedDepositAddress({ orgId: fundingDepositListReader.orgId }) const first = await seedDeposit(firstAddress) const second = await seedDeposit(secondAddress) const third = await seedDeposit(thirdAddress) const project = await seedDeposit(projectAddress) const sibling = await seedDeposit(siblingAddress) const sixth = await seedDeposit(sixthAddress) const foreignAddress = await seedDepositAddress({ orgId: fundingForeign.orgId }) await seedDeposit(foreignAddress) const sandboxAddress = await seedDepositAddress({ environment: 'sandbox', orgId: fundingDepositListReader.orgId, }) await seedDeposit(sandboxAddress) const path = '/v1/funding/deposits' const response = await app.request(`${path}?limit=5`, as(fundingDepositListReader)) expect(response.status).toBe(200) const body = await TestApp.json(response, Funding.schema.listFundingDeposits.Response) expect(body.data.map((deposit) => deposit.id)).toEqual([ sixth.id, sibling.id, project.id, third.id, second.id, ]) expect(body.nextCursor).toBe(Cursor.encode([second.createdAt, second.id])) const next = await TestApp.json( await app.request(`${path}?limit=5&cursor=${body.nextCursor}`, as(fundingDepositListReader)), Funding.schema.listFundingDeposits.Response, ) expect(next.data.map((deposit) => deposit.id)).toEqual([first.id]) expect(next.nextCursor).toBeNull() const projectBody = await TestApp.json( await app.request(path, as(fundingDepositListProjectReader)), Funding.schema.listFundingDeposits.Response, ) expect(projectBody.data.map((deposit) => deposit.id)).toEqual([project.id]) }) }) describe('GET /funding/deposits?recipient', () => { test('requires funding:read and pages recipient deposits across addresses', async () => { const app = transfersApp() const recipient = '0xABcdEFABcdEFabcdEfAbCdefabcdeFABcDEFabCD' const path = `/v1/funding/deposits?recipient=${recipient.toLowerCase()}` expect((await app.request(path)).status).toBe(401) expect((await app.request(path, as(TestApp.key))).status).toBe(403) expect( (await app.request('/v1/funding/deposits?depositAddress=', as(fundingReader))).status, ).toBe(400) expect( ( await app.request( `${path}&depositAddress=TJRabPrwbZy45sbavfcjinPJC18kjpRTv8`, as(fundingReader), ) ).status, ).toBe(200) const firstAddress = await seedDepositAddress({ snapshot: TestFunding.depositAddressSnapshot({ provider: { id: 'relay_account_first', name: 'Relay' }, recipient, }), }) const secondAddress = await seedDepositAddress({ snapshot: TestFunding.depositAddressSnapshot({ provider: { id: 'relay_account_second', name: 'Relay' }, recipient, subsidize: true, }), }) const first = await seedDeposit(firstAddress) const second = await seedDeposit(secondAddress) const third = await seedDeposit(firstAddress) const fourth = await seedDeposit(secondAddress) const fifth = await seedDeposit(firstAddress) const sixth = await seedDeposit(secondAddress) const unrelatedAddress = await seedDepositAddress() await seedDeposit(unrelatedAddress) const foreignAddress = await seedDepositAddress({ orgId: fundingForeign.orgId, snapshot: TestFunding.depositAddressSnapshot({ provider: { id: 'relay_account_foreign', name: 'Relay' }, recipient, }), }) await seedDeposit(foreignAddress) const response = await app.request(`${path}&limit=5`, as(fundingReader)) expect(response.status).toBe(200) expect({ cacheControl: response.headers.get('cache-control'), etag: response.headers.get('etag'), vary: response.headers.get('vary'), }).toMatchInlineSnapshot(` { "cacheControl": "no-store", "etag": null, "vary": "Accept-Encoding, Authorization, Tempo-API-Key", } `) const body = await TestApp.json(response, Funding.schema.listFundingDeposits.Response) expect(body.data.map((deposit) => deposit.id)).toEqual([ sixth.id, fifth.id, fourth.id, third.id, second.id, ]) expect(body.nextCursor).toBe(Cursor.encode([second.createdAt, second.id])) const next = await TestApp.json( await app.request(`${path}&limit=5&cursor=${body.nextCursor}`, as(fundingReader)), Funding.schema.listFundingDeposits.Response, ) expect(next.data.map((deposit) => deposit.id)).toEqual([first.id]) expect(next.nextCursor).toBeNull() }) test('narrows project-attributed keys to their project', async () => { const app = transfersApp() const recipient = `0x${'ab'.repeat(20)}` const projectAddress = await seedDepositAddress({ projectId: fundingProjectReader.projectId, snapshot: TestFunding.depositAddressSnapshot({ provider: { id: 'relay_account_project', name: 'Relay' }, recipient, }), }) const siblingAddress = await seedDepositAddress({ projectId: 'prj_funding_other', snapshot: TestFunding.depositAddressSnapshot({ provider: { id: 'relay_account_sibling', name: 'Relay' }, recipient, }), }) const projectDeposit = await seedDeposit(projectAddress) await seedDeposit(siblingAddress) const body = await TestApp.json( await app.request(`/v1/funding/deposits?recipient=${recipient}`, as(fundingProjectReader)), Funding.schema.listFundingDeposits.Response, ) expect(body.data.map((deposit) => deposit.id)).toEqual([projectDeposit.id]) }) }) describe('GET /funding/deposits?filters', () => { test('AND-combines canonical aliases and includes the matching count', async () => { const app = transfersApp() const snapshot = TestFunding.depositAddressSnapshot({ address: 'TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE', }) const address = await seedDepositAddress({ orgId: fundingDepositFilterReader.orgId, snapshot, }) const deposit = await seedDeposit(address) const unrelatedAddress = await seedDepositAddress({ orgId: fundingDepositFilterReader.orgId, snapshot: TestFunding.depositAddressSnapshot({ provider: { id: 'relay_unrelated', name: 'Relay' }, recipient: `0x${'22'.repeat(20)}`, }), }) await seedDeposit(unrelatedAddress) const query = new URLSearchParams({ depositAddress: snapshot.address, destinationToken: 'usdt0', include: 'totalCount', provider: 'relay', recipient: snapshot.recipient.toLowerCase(), sourceChain: 'tron', sourceToken: 'usdt', status: 'detected', }) const body = await TestApp.json( await app.request(`/v1/funding/deposits?${query}`, as(fundingDepositFilterReader)), Funding.schema.listFundingDeposits.Response, ) expect(body).toEqual({ data: [FundingDeposit.toPublic(deposit)], meta: { totalCount: 1, totalCountCapped: false }, nextCursor: null, }) const empty = await TestApp.json( await app.request( '/v1/funding/deposits?sourceToken=unknown&include=totalCount', as(fundingDepositFilterReader), ), Funding.schema.listFundingDeposits.Response, ) expect(empty).toEqual({ data: [], meta: { totalCount: 0, totalCountCapped: false }, nextCursor: null, }) }) }) describe('GET /funding/deposits/:id', () => { test('returns the owned deposit without private reconciliation state', async () => { const app = transfersApp() const address = await seedDepositAddress() const record = await seedDeposit(address, { providerRequestIds: ['relay-private'], providerState: { request: 'private' }, }) const response = await app.request(`/v1/funding/deposits/${record.id}`, as(fundingReader)) expect(response.status).toBe(200) expect(response.headers.get('cache-control')).toBe(Cache.policies.state) const body = await TestApp.json(response, Funding.schema.getFundingDeposit.Response) expect(body).toEqual(FundingDeposit.toPublic(record)) expect(body).not.toHaveProperty('providerRequestIds') expect(body).not.toHaveProperty('providerState') }) test('hides foreign and absent deposits', async () => { const app = transfersApp() const address = await seedDepositAddress() const record = await seedDeposit(address) expect( (await app.request(`/v1/funding/deposits/${record.id}`, as(fundingForeign))).status, ).toBe(404) expect( ( await app.request( '/v1/funding/deposits/fdp_000000000000000_000000000000000000000000', as(fundingReader), ) ).status, ).toBe(404) }) }) const depositAddressBody = { amount: '100000000', destinationToken: '0x20c00000000000000000000014f22ca97301eb73', recipient: `0x${'11'.repeat(20)}`, refundAddress: 'TJRabPrwbZy45sbavfcjinPJC18kjpRTv8', sourceChain: 'tron', sourceToken: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', } let depositAddressIdempotencySequence = 0 function nextDepositAddressKey() { return `funding_deposit_address_${depositAddressIdempotencySequence++}` } function postDepositAddress( app: ReturnType, options: { body?: unknown headers?: Record | undefined idempotencyKey?: string | undefined key?: { token: string } | undefined } = {}, ) { return app.request('/v1/funding/deposit-addresses', { body: JSON.stringify(options.body ?? depositAddressBody), headers: options.headers ?? { authorization: `Bearer ${(options.key ?? fundingWriter).token}`, 'content-type': 'application/json', 'idempotency-key': options.idempotencyKey ?? nextDepositAddressKey(), }, method: 'POST', }) } function withCreateDepositAddress( id: FundingProvider.ProviderId, createDepositAddress: NonNullable, ) { const provider = providers.find((entry) => entry.id === id) if (!provider) throw new Error(`Missing ${id} provider`) return FundingProvider.from({ ...provider, createDepositAddress }) } function depositAddressProvider( address = 'TJRabPrwbZy45sbavfcjinPJC18kjpRTv8', onCreate: (input: FundingProvider.createDepositAddress.Parameters) => void = () => {}, ) { return withCreateDepositAddress('relay', async (input) => { onCreate(input) return { address, correlation: { checkEndpoint: '/intents/status/v3?requestId=relay_request_1', requestId: 'relay_request_1', }, destinationAmount: '1000000', destinationAmountMin: '1000000', fees: [], sampledAt: '2026-08-04T00:00:00.000Z', } }) } const fundingReader = { id: 'key_funding', orgId: 'org_funding', scopes: ['funding:read'], token: 'secret_funding_reader', } satisfies TestApp.kvStore.Key const fundingAddressListReader = { id: 'key_funding_address_list', orgId: 'org_funding_address_list', scopes: ['funding:read'], token: 'secret_funding_address_list', } satisfies TestApp.kvStore.Key const fundingAddressListProjectReader = { id: 'key_funding_address_list_project', orgId: fundingAddressListReader.orgId, projectId: 'prj_funding_address_list', scopes: ['funding:read'], token: 'secret_funding_address_list_project', } satisfies TestApp.kvStore.Key const fundingDepositListReader = { id: 'key_funding_deposit_list', orgId: 'org_funding_deposit_list', scopes: ['funding:read'], token: 'secret_funding_deposit_list', } satisfies TestApp.kvStore.Key const fundingDepositFilterReader = { id: 'key_funding_deposit_filter', orgId: 'org_funding_deposit_filter', scopes: ['funding:read'], token: 'secret_funding_deposit_filter', } satisfies TestApp.kvStore.Key const fundingDepositListProjectReader = { id: 'key_funding_deposit_list_project', orgId: fundingDepositListReader.orgId, projectId: 'prj_funding_deposit_list', scopes: ['funding:read'], token: 'secret_funding_deposit_list_project', } satisfies TestApp.kvStore.Key const fundingProjectReader = { id: 'key_funding_project', orgId: 'org_funding', projectId: 'prj_funding', scopes: ['funding:read'], token: 'secret_funding_project', } satisfies TestApp.kvStore.Key const fundingForeign = { id: 'key_funding_other', orgId: 'org_funding_other', scopes: ['funding:read'], token: 'secret_funding_other', } satisfies TestApp.kvStore.Key /** Key with funding write access in a different organization. */ const fundingForeignWriter = { id: 'key_funding_other_writer', orgId: fundingForeign.orgId, scopes: ['funding:write'], token: 'secret_funding_other_writer', } satisfies TestApp.kvStore.Key /** Project-attributed funding writer in the owning organization. */ const fundingProjectWriter = { id: 'key_funding_project_writer', orgId: fundingReader.orgId, projectId: fundingProjectReader.projectId, scopes: ['funding:write'], token: 'secret_funding_project_writer', } satisfies TestApp.kvStore.Key const fundingWriter = { id: 'key_funding_writer', orgId: 'org_funding', scopes: ['funding:read', 'funding:write'], token: 'secret_funding_writer', } satisfies TestApp.kvStore.Key function transfersApp(options: TestApp.create.Options = {}) { return create({ ...options, auth: { keys: [ TestApp.key, fundingAddressListProjectReader, fundingAddressListReader, fundingDepositFilterReader, fundingDepositListProjectReader, fundingDepositListReader, fundingForeign, fundingForeignWriter, fundingProjectReader, fundingProjectWriter, fundingReader, fundingWriter, ], }, defaultChainId: options.defaultChainId ?? tempoMainnet.id, }) } function as(key: { token: string }) { return { headers: { authorization: `Bearer ${key.token}` } } as const } let seedDepositAddressSecond = 0 function seedDepositAddress(input: Partial = {}) { const index = seedDepositAddressSecond++ const now = new Date(Date.UTC(2026, 0, 3, 0, 0, index)) return FundingDepositAddress.create(db, { apiKeyId: fundingReader.id, deliveryStrategy: 'provider', environment: 'production', id: FundingDepositAddress.generateId(now), now, orgId: fundingReader.orgId, providerOutputToken: TestFunding.providerOutputToken(), snapshot: TestFunding.depositAddressSnapshot({ provider: { id: `relay_route_${index}`, name: 'Relay' }, recipient: `0x${index.toString(16).padStart(40, '0')}`, }), ...input, }) } let seedDepositSecond = 0 function seedDeposit( address: Awaited>, input: Partial = {}, ) { const index = seedDepositSecond++ const now = new Date(Date.UTC(2026, 0, 4, 0, 0, index)) const sourceTransactionHash = index.toString(16).padStart(64, '0') return FundingDeposit.create(db, { now, providerRequestId: `relay_request_${index}`, snapshot: TestFunding.depositSnapshot(address.id, { provider: address.snapshot.provider, sourceTransactionHashes: [sourceTransactionHash], }), sourceTransactionHash, sourceTransferIndex: 0, ...input, }) }